Forums

Can't use the_title in a custom query? (7 posts)

  1. rbl
    Member
    Posted 1 year ago #

    Hi!
    I'm trying to set up a page template with a custom query that uses the page title to pull posts from the DB where the current page title matches a custom field value.

    In other words, when you visit the page "blue" it will display all posts where custom field "color" is blue.

    The query works when I type the title but doesn't work with the template tag or var like the following example:

    <?php
    $title = the_title();
    $query = 'post_type=any&meta_key=color&meta_value='. $title .'&order=DESC';
    $queryObject = new WP_Query($query);
    while ($queryObject->have_posts()) : $queryObject->the_post();
    ?>

    Any idea what might be wrong or any way to solve this?

    Thanks!
    Ricardo

  2. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

    Try using $title = get_the_title(); to set up your page title variable.

  3. rbl
    Member
    Posted 1 year ago #

    Thanks! It works.

    If it's not an abuse, can you please explain me why the_title doesn't work? It doesn't make sense to me.

    Ricardo

  4. equalmark
    Member
    Posted 1 year ago #

    the_title function outputs the title (like echo's it) where get_the_title doesn't.

  5. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

    the_title() is a function that echoes the post title to the screen. get_the_title() is designed for feeding the post title into a variable for use elsewhere.

  6. rbl
    Member
    Posted 1 year ago #

    So, if I understand correctly by outputting the value, the var in the query becomes empty. Is that it?

  7. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

    In so much as the meta_value becomes useless, yes.

Topic Closed

This topic has been closed to new replies.

About this Topic