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>
'/api/get_posts/?count=-1'
– Jascination Feb 17 at 5:57