简体   繁体   中英

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

如果我想用用户访问页面的所有图像来更新xml文件,我不应该在有人访问该页面时编写create和生成xml文件(因为这会导致过多的开销)-应该当用户将新内容附加到管理控制台中的页面时,我会创建并填充文件吗?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM