wordpress - 如何从媒体库中设置帖子的特色图片
问题描述
如果我使用此功能创建帖子:
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;
}
如何设置媒体库中已存在的特色图片?
解决方案
希望每个人都会喜欢这个创建帖子并设置来自媒体库的特色图片的功能:
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);
推荐阅读
- uiview - 反复隐藏和显示另一个 UIViewController 的视图
- python - 从多个不同长度的二维数组中查找平均数组
- matplotlib - subplots_adjust 不可预测地移动轴?
- r - 在相关矩阵中过滤数据
- regex - 如何将正则表达式转换为 grep 格式
- ruby-on-rails - 为什么我无法在 ruby rails 的视图中访问模型的属性?
- javascript - 父页面上的 javascript 可以在 iframe 内记录击键吗?
- github - 使用 GitHub Actions 自动向 GitHub 存储库发出拉取请求
- c# - 无法为json文件上的详细信息数组生成插入语句,尽管它适用于master?
- sql - 选择数组值的 SQL 语句