在多个帖子中使用附件

时间:2014-01-15 作者:Thanassis

我在一篇文章中有一个附件,我想使用WP API将其附加到另一篇文章,而不必将其与第一篇文章分离。

1 个回复
最合适的回答,由SO网友:Thanassis 整理而成

要做到这一点并不那么简单。在my code change post\\u parent字段中,从具有新帖子Id的附件中删除。

//take all image-attachments from a post to create post for each 
    $images =& get_children( array (
                        \'post_parent\' => $event_id,
                        \'post_type\' => \'attachment\',
                        \'post_mime_type\' => \'image\'
                    ));


            if ( empty($images) ) {
                // no attachments here
            } else { 
                //handle each attachment
                foreach ( $images as $attachment_id => $attachment ) {

                    $this->addPost( $post_id, $attachment_id, $attachment );
                }
....

...
function addPost($post_id, $attach_id, $attach)
        {
            // Create post object

            $new_post = array(
            \'post_title\'    => \'title\',
            \'post_status\'   => \'publish\',
            \'post_author\'   => 1,
            \'post_type\'     => \'post\'
            );

            // Insert the post into the database
            // create new post that want to reattach the attatchment


            $this->unhookFromSavePost(); // see http://codex.wordpress.org/Plugin_API/Action_Reference/save_post#Avoiding_infinite_loops
            $new_post_id = wp_insert_post( $new_post ); //get post\'s id 
            $this->hookToSavePost();
            $attach->post_parent = $new_post_id; // post_id 
            $newAddedAttachment = wp_insert_attachment( $attach );
如果您想复制附件并在更多帖子中使用它,您必须遵循以下步骤:wp_insert_attachment.此外,可以在新对象中复制$attach,但必须取消设置此对象的ID属性。

$new_attach = $attach;
$new_attach->post_parent = $new_post_id;
unset($new_attach[0]);     // unset first property or unset($new_attach[ID]);
wp_insert_attachment( $new_attach);

结束

相关推荐

尝试通过Jetpack JSON API获取自定义发布元数据

我正在使用Wordpress的Jetpack为我的Events 自定义帖子类型,效果良好:https://public-api.wordpress.com/rest/v1/sites/MYSITE/posts/?type=events&number=100然而,这个CPT还包括由Custom Meta Boxes and Fields for Wordpress. 这些字段包括:_ecmb_supporting_bands_ecmb_tickets_avail_ecmb_event_agelim&