将特色图像从一种帖子类型插入另一种

问题描述 投票:1回答:3

我有一个带有特色图片的“活动”帖子类型,我想要它,以便每次保存活动帖子时,它将使用标题,内容,作者和特色图片同时创建博客文章。我有它工作到创建博客文章的点,并添加除特色图像之外的所有字段,因为没有wp_insert_post()函数的特色图像字段。如何从事件发布类型中获取特色图像,该类型是自定义帖子类型并将其添加到常规博客帖子类型?

wordpress post custom-post-type
3个回答
1
投票

我现在已经完全正常工作,并且认为我会在这里分享它,以防其他人试图做同样的事情,并希望看到完整的代码。

add_action( 'save_post', 'create_event_post' );

function create_event_post( $post_id ) {

    // Set the title, thumbnail id, author, and content variables
    $post_title = get_the_title( $post_id );
    $post_type = get_post_type($post_id);
    $post_content = get_post_field('post_content', $post_id);
    $thumbnail_id = get_post_thumbnail_id( $post_id );
    $author_id = get_post_field ('post_author', $post_id);

    // If the post is not "tribe_events", don't create a new post.  
    if ( "tribe_events" != $post_type ) 
        return;

    $new_post = array(
                'comment_status'    =>  'closed',
                'ping_status'       =>  'closed',
                'post_author'       =>  $author_id,
                'post_title'        =>  $post_title,
                'post_content'      =>  $post_content,
                'post_status'       =>  'publish',
                'post_type'     =>  'post'
            );

    remove_action( 'save_post', 'create_event_post' );

    $post_exists = get_page_by_title( $post_title, $output, "post" );

    if ( !empty($post_exists) ) {
        // Update post
        $update_post = array(
            'ID'           =>   $post_exists->ID,
            'post_title'   =>   $post_title,
            'post_content' =>   $post_content,
        );

        // Update the post into the database
        wp_update_post( $update_post );
        set_post_thumbnail( $post_exists->ID, $thumbnail_id );
    }
    else {
        // Create the new post and retrieve the id of the new post
        $new_post_id = wp_insert_post ( $new_post );
        // Set the featured image for the new post to the same image as event post 
        set_post_thumbnail( $new_post_id, $thumbnail_id );
    }           

    // Now hook the action
    add_action( 'save_post', 'create_event_post' );
}

感谢那些回答并希望将来可以帮助其他人的人!


0
投票

在WordPress中,设置特色图像的功能称为set_post_thumbnail($post_id, $thumbnail_id)

你可以阅读更多关于它here

基本上,您可以获取“事件”帖子类型的特色图像的ID,然后在使用set_post_thumbnail创建帖子后将该id传递给wp_insert_post()方法。


0
投票

所以一旦你创建了自定义帖子类型。获取该自定义帖子类型的postId。

然后通过get_post_thumbnail_id( $post_id ); ref:https://codex.wordpress.org/Function_Reference/get_post_thumbnail_id获取该事件帖子的缩略图ID

然后,一旦你创建博客文章获取博客文章的postId然后将缩略图ID分配给该帖子set_post_thumbnail( $post, $thumbnail_id ); ref:https://codex.wordpress.org/Function_Reference/set_post_thumbnail

应该为你想要的东西工作。

© www.soinside.com 2019 - 2024. All rights reserved.