Support » Plugins » Custom Query for Category and Tag

  • jvon42


    I’m pretty new to both WordPress and PHP, so I’d really appreciate any help. Overall, I’m disappointed with the confusing structure (and horrible search function) of WordPress, but I know that I will be able to find an answer to my question here.

    I’m trying to cross-reference a post from Category A with a post from Category B. Both posts have been given Tag C, so for every post in Category A, I’m writing a custom query to pull the post from Category B with the same tag. (It’s a many-to-one relationship, where multiple posts in Category A correspond with the same post in Category B.) Unfortunately, I can’t seem to successfully write a query that calls a specific post from both a category AND a tag. Here’s the code I’m currently using:

    $my_query = new WP_Query("cat=7&tag=$myVariable&showposts=1");

    In theory, then, this should pull all posts from category 7 with the tag $myVariable. If I type in the tag name manually, it still doesn’t work. Strange thing is, I’ve tried looking at all posts with Tag C, and I only see the post from Category A, even though the post from Category B has the same tag. So, the problem here may be with the tagging, not with the query syntax.

    Any help would be greatly appreciated!

Viewing 1 replies (of 1 total)
  • yeah, it’s not easy. the root of it is that tags and categories are in the same table in the database.

    this query will give you posts with both a specific category and tag slug. i use the slug as that’s what works for me, but you could change that to match on the name column…

    global $wpdb;
    $yourCategory = 'whatever';
    $yourTag = 'whatever';
    $querystr =	"
    			SELECT p.* from $wpdb->posts p, $wpdb->terms t, $wpdb->term_taxonomy tt, $wpdb->term_relationships tr, $wpdb->terms t2, $wpdb->term_taxonomy tt2, $wpdb->term_relationships tr2
    			WHERE = tr.object_id
    			AND t.term_id = tt.term_id
    			AND tr.term_taxonomy_id = tt.term_taxonomy_id
    			AND = tr2.object_id
    			AND t2.term_id = tt2.term_id
    			AND tr2.term_taxonomy_id = tt2.term_taxonomy_id
    			AND (tt.taxonomy = 'category' AND tt.term_id = t.term_id AND t.slug = '$yourCategory')
    			AND (tt2.taxonomy = 'post_tag' AND tt2.term_id = t2.term_id AND t2.slug = '$yourTag')
    $pageposts = $wpdb->get_results($querystr, OBJECT);
    if ($pageposts):
    	foreach ($pageposts as $post):
    		// do regular WordPress Loop stuff in here
    else :
    	// nothing found
Viewing 1 replies (of 1 total)
  • The topic ‘Custom Query for Category and Tag’ is closed to new replies.