Can not concatenate WordPress function to query string (2 posts)

  1. joshuahornby
    Posted 3 years ago #

    On my page the_category()displays the name of the current category the user has clicked on, I want to use this and pass it into my function to display the tags in the current category. The function works if you manually type in the category name.

    I have tried to concatenate the the_category()to the end of the query string but this doesn't work and just prints out all the tags in the blog.

    <div class="heading"><h1>Category:<?php the_category(); ?></h1></div>
        $custom_query = new WP_Query('posts_per_page=-1&category_name=' .the_category());//This will work if I enter ='cheese' for example
        if ($custom_query->have_posts()) :
            while ($custom_query->have_posts()) : $custom_query->the_post();
                $posttags = get_the_tags();
                if ($posttags) {
                    foreach($posttags as $tag) {
                        $all_tags[] = $tag->term_id;
  2. vtxyzzy
    Posted 2 years ago #

    I think the problem is that the_category() returns the Name of the category, and the category_name parameter, despite its name, requires the slug of the category.

    I think this is what you want:

    $cats = get_the_category();
    $slug = $cats[0]->slug;
    $custom_query = new WP_Query('posts_per_page=-1&category_name=' .$slug);

Topic Closed

This topic has been closed to new replies.

About this Topic