0

I'm trying to pull in posts in a page that are tagged with the same page title. For example, if the page is called Banana Pants, then I can call all associated posts manually like this:

    <?php
    query_posts( array(
    'tag_slug__in' => array('Banana Pants')
    )); 
    while (have_posts()) : the_post (); ?>

However, I'd like to do this automatically. When I try to place it as a variable, it doesn't work:

    <?php
    var $project_title = the_title();
    query_posts( array(
    'tag_slug__in' => array($project_title)
    )); 
    while (have_posts()) : the_post (); ?>

What am I doing incorrectly? Or, is there a better method?

1 Answer 1

0

First of all, don't use query_posts

Form Codex:

Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.

(the picture there is by this site mod @Rarst.

Main problem is that the_title() echos the title, does not return the title.

For that scope you have to use get_the_title().

Also, PHP is not javascript, don't use var before the variables:

<?php
$project_title = get_the_title();
$query = new WP_Query( array(
  'tag_slug__in' => array( $project_title )
) );
while ( $query->have_posts() ) : $query->the_post(); ?>
1
  • Perfect—that did the trick! Thanks for the query_posts vs. new WP_Query method. I've applied that method. Thanks!
    – Marc P
    Commented Apr 29, 2014 at 20:55

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.