Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to call a list of my Wordpress posts and save them to a Javascript array of objects (JSON, really). I want something like:

var articles = [
  {
  title: 'Title 1',
  author: 'Author 1',
  byline: 'Byline 1'
  },{
  title: 'Title 2',
  author: 'Author 2',
  byline: 'Byline 2'
  }
]

I'm new to PHP so don't quite understand how looping in and out of the <?php ?> tags works, nor how variables and functions work in this sense. I'm trying the following:

<script>
    var articles = [];
    <?php
        $args = array( 'numberposts' => -1); 
        $posts= get_posts( $args );
        if ($posts) {
            foreach ( $posts as $post ) { ?> // exit PHP
                var obj = {}; // Create a JS object
                obj.title = <?php the_title(); ?>; // Append the title to the object
                obj.byline = <?php the_excerpt(); ?>; // Append the byline
                articles.push(obj); // Push object into the array
            <?php }
        }
    ?>
</script>
share|improve this question
    
See if this helps wordpress.org/plugins/json-api –  elclanrs Feb 17 at 5:45
    
@elclanrs That looks cool, although it seems like you can only get a maximum of 10 posts returned using this API and I need all of them... (the documentation seems to be non-existent though, please point me in the right direction if wrong) –  Jascination Feb 17 at 5:52
    
The documentation looks good wordpress.org/plugins/json-api/other_notes –  elclanrs Feb 17 at 5:55
    
@elclanrs Ah, didn't see it. For anyone who stumbles across this, the correct way to do it is: '/api/get_posts/?count=-1' –  Jascination Feb 17 at 5:57
add comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

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

Browse other questions tagged or ask your own question.