开发者

Wordpress: How should I keep an xml-file updated with the images attached to a page?

If I want to keep an xml file updated with all the images that a us开发者_C百科er has attched to a page, I shouldn't write create and generate an xml-file everytime someone visits that page (because it would cause too much overhead) - should I create and fill the file when the user attaches new content to the page in the admin console instead?


First, you will need to create directory under wp-content. Lets called it wp-content/xmlimages/ Now, copy this code and paste it to wp-content/plugins/cr-attachmentpost2xml.php:

<?php
/*
Plugin Name: CR Attachment Post To XML
Plugin URI: http://bayu.freelancer.web.id/search/plugin
Description: Automatically create XML files for each post that list post attachment of that particular post.
Version: 0.1
Author: Arief Bayu Purwanto
Author URI: http://bayu.freelancer.web.id/

*/

add_action('publish_post', 'cr_attachmentpost2xml_publish_post_hook');

//add_action('admin_menu', 'cr_attachmentpost2xml_test');

function cr_attachmentpost2xml_publish_post_hook( $post_id ){
    __cr_attachmentpost2xml_impl( $post_id );
    return $post_id;
}

function cr_attachmentpost2xml_test(){
    __cr_attachmentpost2xml_impl( 738 );
}

function __cr_attachmentpost2xml_impl( $post_id ){
    $udir = wp_upload_dir();
    $writepath = $udir['basedir'] . '/xmlimages/';
    $attachment = get_children( 'post_type=attachment&post_parent=' . $post_id);

    if(wp_is_post_revision($postId)) return $post_id;
    //print_r($attachment);
    $xml = "<?xml version=\"1.0\"?>";
    $xml .= "<attachments>";

    foreach($attachment as $att){
        $image_src = wp_get_attachment_image_src( $att->ID );
        $xml .= "<attachment>";
        $xml .= "<id>{$att->ID}</id>";
        $xml .= "<date>{$att->post_date}</date>";
        $xml .= "<title>{$att->post_title}</title>";
        $xml .= "<mime_type>{$att->post_mime_type}</mime_type>";
        $xml .= "<url>".$image_src[0]."</url>";

        $xml .= "</attachment>";
    }
    $xml .= "</attachments>";
    file_put_contents($writepath . $post_id . ".xml", $xml);
    //echo "$xml";
}

WARNING: Don't except something special here, as it's just a quick & dirty code. Hope it work the way to want and if you do use this code, don't forget to check for any security hole it might introduce.


Any particular reason why you need this? This data is recorded by WordPress so why not instead create a simple API that returns XML on request? There's no sense in duplicating data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜