首页 > 解决方案 > 如何从媒体库中设置帖子的特色图片

问题描述

如果我使用此功能创建帖子:

function write_post_with_featured_image( $post_title, $categories ) {
    $category_names_array = explode( ",", $categories );

    $category_ids = array( );
    foreach ( $category_names_array as $category_name ) {
        $category_id = get_cat_ID( $category_name );
        array_push( $category_ids, $category_id );
    }

    // Create post object
    $my_post = array( 
        'post_title'    => wp_strip_all_tags( $post_title ),
        'post_status'   => 'publish',
        'post_author'   => 1,
        'post_category' => $category_ids,
    );

    // Insert the post into the database
    $post_id = wp_insert_post( $my_post );
    echo "post_id: " . $post_id;
}

如何设置媒体库中已存在的特色图片?

标签: wordpressdynamic-featured-image

解决方案


希望每个人都会喜欢这个创建帖子并设置来自媒体库的特色图片的功能:

function write_post_with_featured_image($post_title, $categories, $image_in_library_url) {
        $category_names_array = explode(",", $categories);

        $category_ids = array();
        foreach ($category_names_array as $category_name) {
            $category_id = get_cat_ID($category_name);
            array_push($category_ids, $category_id);
        }

        // Create post object
        $my_post = array(
          'post_title'    => wp_strip_all_tags($post_title),
          'post_status'   => 'publish',
          'post_author'   => 1,
          'post_category' => $category_ids
        );


        // Insert the post into the database
        $post_id=wp_insert_post( $my_post );
        echo "post_id:" . $post_id;

        //Get Image Attachment Id
        $attachment_id = attachment_url_to_postid( $image_in_library_url );
        echo "attachment_id:" . $attachment_id;

        // And finally assign featured image to post
        set_post_thumbnail( $post_id, $attachment_id );
        echo "featured image added";
    }
}

$post_title = 'My Super Post';
$categories = 'Category1,Category2';
$image_in_library_url = "http://localhost/wp-content/uploads/2018/06/my-super-image.jpg";
write_post_with_featured_image($post_title,$categories,$image_in_library_url);

推荐阅读