Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

    "post_title","post_title","post_title"

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;
                wp_reset_query();
                ?>]">

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

share|improve this question
add comment

2 Answers

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(
  'numberposts'=>-1,
  'category'=>0
 ));

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
1  
So they do, updated answer :). Please remember to accept correct answers. –  Stephen Harris Apr 4 '12 at 13:21
show 3 more comments

change that line:

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

to:

<?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
add comment

Your Answer

 
discard

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.