On a page listing terms from my ‘source’ taxonomy, I loop through foreach term…
foreach ($all_source_terms as $source_term) {
// some stuff
echo $source_term->count;
}
When I echo $source_term->count;
, it outputs a count of posts for that term.
In one term’s case, the output value is 2.
But, on my taxonomy-source.php
page (where I do a WP_Query for ‘post_type
‘ ‘any
‘ in order to show that term’s posts etc), this value appears as 0 and no content is displayed. Here is the query, FYI…
$queried_object = get_queried_object();
$object_prefixed = $queried_object->taxonomy.'_'. $queried_object->term_id;
$posts_per_page = 300;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
// pagination
'nopaging' => false,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
// order
'orderby' => 'date',
// 'order' => 'DESC',
// posts
'post_type' => 'any',
'status' => 'publish',
// 'offset' => $offset,
// taxonomies
'tax_query' => array(
array(
'taxonomy' => 'source',
'field' => 'slug',
'terms' => $queried_object->slug,
),
),
);
// the query
$posts_source = new WP_Query($args);
Now, the above rogue term in question is ID 1169. When I go in to phpMyAdmin and search tables for 1169, I see 2 results in wp_term_relationships, for object_ids 129898 and 129900.
However, when I put those IDs in to the WordPress post-edit page (post.php?post=129898&action=edit), WordPress says: “You attempted to edit an item that doesn’t exist. Perhaps it was deleted?”
Indeed, when I search for either of those object_ids in phpMyAdmin, NONE are found.
What’s going on here?
I wondered whether the posts existed but I had undone the custom-post-type registration. But, hey, the posts are not found in phpMyAdmin.
So probably the posts HAVE been deleted, but no-one told term-relationships?
This is likely to be the case for several terms.
What code can I use to properly fix term relationship counts – ie. remove relationships for posts that don’t exist?