如何让wordpress自动添加特色图片?

时间:2014-06-24 13:06:52

标签: php wordpress

我想让wordpress在新帖子中自动添加精选图片。

条件:

  • 帖子类别ID必须为3
  • 每位作者/用户都有自己的形象。
  • 图片(已上传)具有以下名称格式: [firstname author] - [lastname author] .jpg。

例如;当Steve Jobs提交帖子时,提交的帖子类别ID应为3,此帖子的精选图片集应为'steve-jobs.jpg'。

最终工作代码:

function set_featured_image_blog_post() {
    global $post;
    $already_has_thumb = has_post_thumbnail( $post->ID );
    $post_category = get_the_category( $post->ID );
    if ( !$already_has_thumb && $post_category[0]->cat_ID  == 3 )  {
        if( $post->post_author == 3 ){
            set_post_thumbnail( $post->ID, 165 );
        }
        else if( $post->post_author == 4 ){
            set_post_thumbnail( $post->ID, 166 );
        }       
    }
}

add_action('the_post', 'set_featured_image_blog_post');
add_action('save_post', 'set_featured_image_blog_post');
add_action('draft_to_publish', 'set_featured_image_blog_post');
add_action('new_to_publish', 'set_featured_image_blog_post');
add_action('pending_to_publish', 'set_featured_image_blog_post');
add_action('future_to_publish', 'set_featured_image_blog_post');

1 个答案:

答案 0 :(得分:0)

最终代码:

function set_featured_image_blog_post() {
    global $post;
    $already_has_thumb = has_post_thumbnail( $post->ID );
    $post_category = get_the_category( $post->ID );
    if ( !$already_has_thumb && $post_category[0]->cat_ID  == 3 )  {
        if( $post->post_author == 3 ){
            set_post_thumbnail( $post->ID, 165 );
        }
        else if( $post->post_author == 4 ){
            set_post_thumbnail( $post->ID, 166 );
        }       
    }
}

add_action('the_post', 'set_featured_image_blog_post');
add_action('save_post', 'set_featured_image_blog_post');
add_action('draft_to_publish', 'set_featured_image_blog_post');
add_action('new_to_publish', 'set_featured_image_blog_post');
add_action('pending_to_publish', 'set_featured_image_blog_post');
add_action('future_to_publish', 'set_featured_image_blog_post');