0

I'm working on a small function for a WordPress site, and can't figure why my function is echoing the data on my webpage.

My function is:

function get_post_titles($args) {
    $titles = array();
    $posts = new WP_Query($args);
    while ($posts->have_posts()){
        $posts->the_post();
        $titles[] = the_title();
    }
    return $titles;
}

and I call it in a separate .php file:

<?php
$titles = get_post_titles($args);
?>
<select>
    <option selected="selected">Choose an Article</option>
    <?php
        foreach($titles as $title){
            ?> <option> $title </option><?php //this isn't working, pls ignore for this post
        }   
    ?>
</select>
...

The result is a webpage with a Select box (yay!) but for some reason, the page also shows ALL of the titles in a row (it outputs the full array).

I would expect that if I had say, echo get_post_titles($args), but nowhere in my code do I ask it to echo. Why is my array visible?

I think it's because of my $titles = get_post... line. But again, why is it displaying $titles instead of simply declaring/assigning the variable?

(I know there's a WordPress SE site, but I think this is more directly a PHP issue than WP issue. However, if I should post over there instead, let me know).

1

2 Answers 2

2

the_title() displays the title. You should use get_the_title() instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Whelp that's exactly it! I studied my code for about an hour, and even learned yesterday about get_the_[whatever] vs the_[whatever] and completely overlooked that somehow...Thanks so much for pointing me in the right direction! :D
My pleasure. As the other answer shows... many ways to skin a cat. I just prefer the lazy route, i.e. less typing, but both work.
2

From Wordpress Documentation, following is the usage of the_title:

the_title( $before, $after, $echo );

$echo (Boolean) (optional) Display the title (TRUE) or return it for use in PHP (FALSE).

Default: TRUE

You can do the following (set the third argument to false):

$titles[] = the_title('','',false);

2 Comments

Thanks very much for the expanded info!
@BruceWayne happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.