如何从媒体库设置帖子的特色图片

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

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

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;
}

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

php wordpress wordpress-featured-image
1个回答
3
投票

希望每个人都会喜欢这个创建帖子并从媒体库中设置其特色图像的功能:

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);
© www.soinside.com 2019 - 2024. All rights reserved.