相关文章推荐
逼格高的作业本  ·  AIX Toolbox for Open ...·  1 月前    · 
刚失恋的水煮肉  ·  curl ...·  2 周前    · 
谈吐大方的电脑桌  ·  spring ...·  5 月前    · 
逃跑的棒棒糖  ·  Python爬虫:Selenium+ ...·  1 年前    · 

从一个帖子类型到另一个帖子类型插入特色图片

1 人关注

我有一个带有特色图片的 "事件 "帖子类型,我想让它在每次保存一个事件帖子时,同时使用标题、内容、作者和特色图片创建一个博客帖子。我已经开始工作了,它创建了博文并添加了所有的字段,除了特色图片,因为在wp_insert_post()函数中没有特色图片字段。我怎样才能从自定义帖子类型的事件帖子中获得特色图片,并将其添加到常规的博客帖子类型中?

wordpress
post
custom-post-type
Kang Yun
Kang Yun
发布于 2018-03-05
3 个回答
Kang Yun
Kang Yun
发布于 2018-03-05
0 人赞同

我现在已经完全实现了这个功能,我想我应该在这里与大家分享,以防有人想做同样的事情,并希望看到代码的全部内容。

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' );

谢谢那些回答的人,希望这能在未来帮助到其他人

T. Ruxton
T. Ruxton
发布于 2018-03-05
0 人赞同

在WordPress中,设置特色图片的函数叫做 set_post_thumbnail($post_id, $thumbnail_id)

你可以 在这里 阅读更多关于它的信息

基本上,你可以得到你的 "事件 "帖子类型的特色图片的ID,然后在用 wp_insert_post() 创建帖子后将该ID传递给 set_post_thumbnail 方法。

cjmling
cjmling
发布于 2018-03-05
0 人赞同

因此,一旦你创建了自定义帖子类型。获取该自定义帖子类型的postId。