我使用下面的代码根据帖子标题中的关键字将帖子批量分配到某个类别。
以下代码应标识标题中所有带有关键字“ addiction”的帖子,并将其添加到ID为6和8的类别中。
由于某些原因,它不再起作用。
add_action('publish_post', 'update_categories');
function update_categories(){
global $wpdb, $post;
// set the category ID to update
$categories = array(6,8);
echo "updating";
$postids = array();
// this is to tell the script to only pull posts that are labeled "publish"
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => - 1,
);
$my_query = null;
$my_query = new WP_Query($args);
if ($my_query->have_posts()):
while ($my_query->have_posts()):
$my_query->the_post();
$postids[] = $my_query->post->ID;
endwhile;
endif;
wp_reset_query(); // Restore global post data stomped by the_post().
$i = 0;
$num_of_posts = $my_query->post_count;
// running through all the posts
while ($num_of_posts > $i):
// getting the post title
$post_title = get_the_title($postids[$i]);
if (stripos($post_title, 'addiction') !== false):
// add a category
wp_set_post_categories($postids[$i], $categories, true);
endif;
$i++;
endwhile;
}
你们能帮忙吗?
答案 0 :(得分:0)
我编写了带有调试的代码,以检查什么和什么不起作用。根据您的需要更新值,并检查其是否有效。
//To Add Categories to all posts containing specific word in post title
function add_categories_to_posts(){
echo "<br><br>Updating Categories Started <br><br>";
$query_args = array(
'post_type' => 'post', //post type - default post type is 'post'
'post_status' => 'publish', //published posts
'posts_per_page' => - 1, //-1 is used to get all posts
);
$all_posts = new WP_Query($query_args);
$new_categories_list = array(6,8,10,22);
$working_categories = []; //Debug : list of categoires that does not exists from given list
$not_working_categories = []; //Debug : list of categoires that exists from given list
$updated_posts_ids = []; //Debug : list of post id's that updated categories
$not_updated_posts_ids = []; //Debug : list of post id's that did not updated any categories
//Debug : check if post categories exists
foreach ($new_categories_list as $key => $category) {
$exists = term_exists($category,'category');
if ( $exists !== 0 && $exists !== null ) {
$working_categories[] = $category;
}
else{
$not_working_categories[] = $category;
}
}
if($all_posts->have_posts()){
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$title = get_the_title();
$ID = get_the_ID();
if (stripos($title, 'addiction') !== false){
$updated_posts_ids[] = $ID;
wp_set_post_categories($ID, $working_categories, true);
//set true as last argument since you don't want to override existing categories
} else{
$not_updated_posts_ids[] = $ID;
}
endwhile;
wp_reset_postdata();
}
echo "<br>Affected Post ID's array: ";
var_dump($updated_posts_ids);
echo "<br><br>Unaffected Post ID's array: ";
var_dump($not_updated_posts_ids);
echo "<br><br>Updating Categories Ended <br><br>";
}
add_action('save_post','add_categories_to_posts');