0

I'm returning to WP after some time away, and find I've forgotten what little I knew.

I have some pages on a site that display a post of given category, which was done with a line like: query_posts($query_string . '&cat=2');

followed by: if ( have_posts() ) : while ( have_posts() ) : the_post(); etc. etc. ending with (else) 'Sorry, no posts matched your criteria'

I have defined a category 'Services', and assigned a test post to this category. I can see in wp_terms that the category has the term_id of 2 and name of 'Services', but the post isn't getting picked up.

Where is the post 'told' what its category is? Should I be expecting to see a field for category_id (or cat_id) somewhere? It's certainly not in the wp_posts record.

Or, in other words, where is the query string &cat=2 picked up?

It certainly used to work, but that was a while ago and maybe some updates to WP or PHP now require a change?

1 Answer 1

3

wp_terms, wp_term_taxonomy, wp_term_relationships and wp_term_meta these 4 tables powers the WordPress taxonomy world. You'll find the relation between post and term within these 3 tables wp_terms, wp_term_taxonomy, wp_term_relationships. You have to start journey from wp_term_relationships. If you wanna know more about DB schema https://codex.wordpress.org/Database_Description https://code.tutsplus.com/tutorials/understanding-and-working-with-data-in-wordpress--cms-20567

And query_posts() is harmful and bad practice, it overrides the WordPress main query. Better you should use a custom query.

$query = new WP_Query( array(
        'cat' => 2, // category id goes here
    ) );

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
        // do the whatever you wanna do inside the loop
    endwhile;
endif;
1
  • I found that changing my opening line to 'query_posts('cat=2')' (doing away with the $query_string variable) worked as I wanted. Quite why there's been a change I do not know. I should have explained that this is only a 'partial' WP site, most of the pages are regular HTML/PHP, just a few are in WP so that the site owner can make edits.
    – Tim Dawson
    Commented Feb 12, 2018 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.