WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to list post_title's in this specific format (note the last title in the list must not have a comma)


I thought a mini-loop might work. Here's what I'm using

            <?php query_posts('cat=0$posts_per_page=-1'); // query to show all posts independant from what is in the center;
                if (have_posts()) :
                    while (have_posts()) : the_post(); ?>
                        '<?php the_title(); ?>',
                    <?php endwhile; endif;

But I need the final post_title to have no trailing comma?

share|improve this question
up vote 2 down vote accepted

I'm not sure of the context for this, but query_posts probably isn't what you want to use. (See this answer).

(Untested). I would use get_posts:

$posts = get_posts(array(

And then use wp_list_pluck to get the titles:

$post_titles = wp_list_pluck($posts,'post_title');
$post_titles = array_map('esc_html',$post_titles);

Finally, the php implode function an list them with commas:

echo '"'.implode('","',$post_titles).'"';
share|improve this answer
Thanks Stephen. I'm trying to use Twitter Bootstrap's "TypeAhead" javascript plugin [link] twitter.github.com/bootstrap/javascript.html#typeahead And the formatting is this <input type="text" class="span3" style="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source='["Alabama","Alaska","Arizona"]> – TheLoneCuber Apr 4 '12 at 11:56
So I'm replacing the data-source of city names with data-source of post titles. – TheLoneCuber Apr 4 '12 at 12:08
Use the above to echo the titles in the data-source attribute :) – Stephen Harris Apr 4 '12 at 12:12
Almost works Stephen. But the data-source values need to be enclosed in quotes "the_title","the_title","the_title" – TheLoneCuber Apr 4 '12 at 12:36
So they do, updated answer :). Please remember to accept correct answers. – Stephen Harris Apr 4 '12 at 13:21

change that line:

'<?php the_title(); ?>',


<?php if( $wp_query->current_post ) { echo ', ';} ?>'<?php the_title(); ?>'
share|improve this answer
I went with @StephenHarris's method. Thanks anyway Michael. – TheLoneCuber Apr 4 '12 at 22:26

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.