WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Custom query by category AND tag doesn't work? (3 posts)

  1. Matthew Gerring
    Member
    Posted 5 years ago #

    This works-

    $my_query = new WP_Query('tag=foo');

    And this works-

    $my_query = new WP_Query('category_name=bar');

    But not this-

    $my_query = new WP_Query('tag=foo&category_name=bar');

    I remember hearing something about categories and tags being the same thing in WP 2.7, so I tried this-

    $my_query = new WP_Query('tag=foo+bar');

    And that doesn't work either.

    Any suggestions?

  2. Matthew Gerring
    Member
    Posted 5 years ago #

    and yes I am aware that I need to use an actual ampersand and not &

  3. Matthew Gerring
    Member
    Posted 5 years ago #

    If anyone's interested, here's my solution.

    Apparently, cross-referencing tags and categories is impossible without a custom SELECT query, since both are stored in the same database. But instead of having a giant, unwieldy SELECT query in my template files, I stuck it into a custom function that I can re-use later, like this-

    function fwpt($cat, $tag)
    {
    global $wpdb;
    $yourCategory = $cat;
    $yourTag = $tag;
    $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 p.id = tr.object_id
    			AND t.term_id = tt.term_id
    			AND tr.term_taxonomy_id = tt.term_taxonomy_id
    			AND p.id = 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')
    			";
    return $querystr;
    }

    And then referenced it where I needed it like this-

    if (is_tag()) {
    
    		$tagname = get_query_var('tag');
    		$taxquery = fwpt('foo',$tagname);
    		$pageposts = $wpdb->get_results($taxquery, OBJECT);
    		foreach ($pageposts as $post):
    		setup_postdata($post);
    		include (TEMPLATEPATH.'/stuff_to_do.php');
    		endforeach;
    
    		} else { 
    
    		$deliverables = new WP_Query('category_name=foo');
            while ($deliverables->have_posts()) : $deliverables->the_post();
    		include (TEMPLATEPATH.'/stuff_to_do.php');
    		endwhile;
    		}

    Cumbersome, yes, but it gets the job done.

Topic Closed

This topic has been closed to new replies.

About this Topic