This piece of code works for me, but I have more than 10,000 posts in post types on my website, and by calling posts_per_page => -1
The loading speed of the site is very low and the RAM and CPU are heavily involved and become 100%.
I want to optimize this code so that there is no need to call posts_per_page => -1 and load all the posts in Admin Ajax.
function set_object_terms(){
global $post;
global $wp_taxonomies;
$args = array(
'post_type' => array('music','musicvideo','remix','palylist','album'),
'post_status' => 'publish',
'posts_per_page' => -1,
);
$index_posts = new WP_Query( $args );
if( $index_posts->have_posts() ){
while( $index_posts->have_posts() ){ $index_posts->the_post();
$postid = get_the_ID();
$terms = get_post_meta($postid,'meta_info_singername',true);
if(is_array($terms) && !empty($terms)) :
$taxonomy = 'singers';
$default_terms = array();
foreach ($terms as $term_id) {
$tmp_term_id = get_term_by('id', $term_id, 'singers');
if ($tmp_term_id) {
$default_terms[] = (int) $tmp_term_id->term_id;
$default_terms[] = (int) $tmp_term_id->parent;
}
}
$defaults = array($taxonomy => $default_terms);
$postid = get_the_ID();
wp_set_object_terms( $postid,$defaults[$taxonomy], $taxonomy);
else :
$postid = get_the_ID();
$termids = '';
$taxonomy = 'singers';
wp_set_object_terms( $postid,$termids, $taxonomy);
endif;
}
wp_reset_postdata();
}
}
add_action('init', 'set_object_terms', 20 );
New contributor
Mr Saman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.