Search code examples
phpwordpresstags

How can I query Multiple word tags in Wordpress


A site I am developing (running WordPress 3.4.2) features a sidebar with a list of tags.

When a tag link is clicked, the user is taken to tag.php which contains a custom query to display all posts related to the tag in question.

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(array( 'post_type' => array('blog','news'),          'tag'=>single_tag_title('', false), 'posts_per_page' => -1, 'caller_get_posts' => 1, 'paged'    => $paged));

This is followed by a loop that spits out a summary of each post. Everything works OK when a single-word tag (eg. 'windows') is clicked, but when a multi-word tag (eg. 'operating system') is clicked, the query does not find any posts.

I understand that WordPress tags are designed to be single words, and I know that I can fix the issue by hyphenating all multi-word tags.

However, I'd prefer to continue using non-hyphenated multi-word tags for ease of readability.


Solution

  • Many thanks for your help David - In the end a tip from Wordpress moderator @alchymyth led me to this simpler solution:

    I was using single_tag_title and needed to use the tag slug. Here's the fix in bite-size steps (all changes in tag.php):

    1. set a variable for the current tag:

      $current_tag = single_tag_title("", false);
      
    2. In query_posts change:

      'tag'=>single_tag_title('', false)
      

      to...

      'tag_slug__and'=>array($current_tag)
      

    ...so the full code is:

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $current_tag = single_tag_title("", false);
    
    query_posts(array( 'post_type' => array('blog', 'news'), 'tag_slug__and'=>array($current_tag), 'posts_per_page' => -1, 'caller_get_posts' => 1, 'paged' => $paged));
    

    Here's the forum post: http://wordpress.org/support/topic/query_posts-does-not-return-results-for-multiple-word-tags?replies=3#post-4018519

    Thanks again.