不久前,我在我的一个网站上添加了一个功能,可以将一组帖子从一种类型更改为另一种类型。我记不清确切的原因,但我已经把它挖了出来,并对它进行了一点更新,它已经过测试,并且工作正常。
将此功能放入functions.php 这样就可以在你博客的任何地方调用它。
/**
* Change the type of a WP_Post object
*
* @param required array $posts An array of post objects to update
* @param required string $change_to The post type to change the selected objects to
* @param string $change_from The post type to change the selected objects from (ignored if \'false\')
*/
function my_change_post_type($posts, $change_to, $change_from = false){
/** Ensure that an array of objects has been passed */
if(!is_array($posts))
return new WP_Error(\'change_post_type\', __(\'<h4>Function \\\'my_change_post_type()\\\'</h4>The $posts array is empty, unable to proceed.\'));
/** Ensure that $change_to is a valid post type */
if(!post_type_exists($change_to))
return new WP_Error(\'change_post_type\', __(sprintf(\'<h4>Function \\\'my_change_post_type()\\\'</h4>The value of the <b>$change_to</b> parameter (<b>%1$s</b>) is not a valid post type, unable to proceed.\', $change_to)));
/** Loop through each object in the $posts array... */
foreach($posts as $key => $post) :
/** Ensure that this $post is actually a \'WP_Post\' object... */
if(!is_a($post, \'WP_Post\')) : // It is not, so unset this $post and continue to the next (no need to update what hasn\'t changed)
unset($posts[$key]);
continue;
endif;
/** Check whether or not $change_from has been set... */
if($change_from) : // It has
/** Ensure that $change_from is formatted as an array... */
if(!array()) // It is not, so make it an array
$change_from = (array)$change_from;
/** Check if the post type needs to be changed... */
if(in_array($post->post_type, $change_from)) : // It does, so change it
$post->post_type = $change_to;
else :
unset($posts[$key]); // It does not, so unset this $post (no need to update what hasn\'t changed)
endif;
else : // It has not, so change the post type
$post->post_type = $change_to;
endif;
endforeach;
/** Finally, update $posts (if there are any) */
if(!empty($posts)) :
wp_update_post($posts);
return true;
else:
return false;
endif;
}
如何使用要使用此函数,只需向其传递
WP_Post
对象和要将其设置为的帖子类型。
正如我在对你的问题的评论中提到的,我建议使用你想要更改的对象的ID,首先只抓取那些帖子,如下所示-
$args = array(
\'post__in\' => array(12,58,79,105)
);
$posts = get_posts($args);
$result = my_change_post_type($posts, \'page\');
然而,如果你不想挑出某些对象,只想将所有帖子更改为页面,你可以抓取所有帖子-
$args = array(
\'post_type\' => \'post\'
);
$posts = get_posts($args);
$result = my_change_post_type($posts, \'page\');
如果需要,您还必须选择从多个帖子类型更改为单个类型(例如,如果您决定不推荐几个自定义帖子类型,并希望将其中的所有对象设置为帖子)-
$posts = get_posts(array());
$result = my_change_post_type($posts, \'page\', array(\'cpt_1\', \'cpt_2\'));
错误处理另外,如果需要,您可以检查
my_change_post_type()
函数并停止执行。
if(is_wp_error($result)) :
wp_die($result);
endif;