[WordPress] Find posts that are not tagged with at least one tag in a range of tags.
<?php | |
add_action( 'admin_init', 'acme_query_for_untagged_posts' ); | |
/** | |
* Query for all public posts that are not tagged with at least | |
* one term from a set of term IDs. | |
*/ | |
function acme_query_for_untagged_posts() { | |
$args = array( | |
'post_type' => 'post', | |
'post_status' => 'public', | |
'posts_per_page' => -1, | |
'tax_query' => array( | |
array( | |
'taxonomy' => 'my_custom_tax', | |
'field' => 'term_id', | |
'terms' => array( 10, 15, 20, 25, 30 ), | |
'operator' => 'NOT IN' | |
) | |
) | |
); | |
$acme_query = new WP_Query( $args ); | |
/* At this point, you can return the result, iterate through | |
* the query and update the posts, etc. | |
*/ | |
} |
<?php | |
/* This gist assumes that the query in | |
* https://gist.github.com/tommcfarlin/6537bcaf6ac77e3bbfeb#file-query-untagged-posts-php | |
* returns the instance of $acme_query that's defined in the function. | |
* | |
* Also note that this is contingent upon acme_query_for_untagged_posts() passing | |
* post_type => 'my_cpt' rather than 'post'. | |
*/ | |
$acme_query = acme_query_for_untagged_posts(); | |
/* Define an array of integers each of which corresponds to a tag that needs | |
* to be added to each post. In this case, it's only adding the term that | |
* has the ID of 2. | |
*/ | |
$term_ids = array( 2 ); | |
if ( $acme_query->have_posts() ) { | |
while ( $acme_query->have_posts() ) { | |
$acme_query->the_post(); | |
wp_set_object_terms( get_the_ID(), $term_ids, ‘my_custom_tax’, TRUE ); | |
} | |
} |
<?php | |
/* This gist assumes that the query in | |
* https://gist.github.com/tommcfarlin/6537bcaf6ac77e3bbfeb#file-query-untagged-posts-php | |
* returns the instance of $acme_query that's defined in the function. | |
*/ | |
$acme_query = acme_query_for_untagged_posts(); | |
/* Define an array of integers each of which corresponds to a tag that needs | |
* to be added to each post. In this case, it's only adding the term that | |
* has the ID of 2. | |
*/ | |
$term_ids = array( 2 ); | |
if ( $acme_query->have_posts() ) { | |
while ( $acme_query->have_posts() ) { | |
$acme_query->the_post(); | |
wp_set_post_terms( get_the_ID(), $term_ids, ‘my_custom_tax’ ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment