This code is working fine and pulling the blog posts but the only problem is that i want the data to be in a json array so that i can create an api with that and show posts outside…
<?php
require('/home/dealicopter/public_html/wp-load.php');
function wpdocs_custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
$args = array(
'posts_per_page' => 10,
'cat' => 7,
);
query_posts($args); if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
$permalink = the_permalink();
$title = the_title();
$age = array("id"=>$permalink, "title"=>$title);
?>
<?php echo json_encode($age); ?>
<?php endwhile; else: echo "[]"; endif; ?>
<?php wp_reset_query(); ?>
2
Answers
WordPress comes with an build-in API that returns JSON. you can hook in this as follows
https://example.com/wp-json/wp/v2/posts/?filter%5Bposts_per_page%5D=-1
API Documentation
if you want to make custom code I recommend using
wp_send_json()
create a new template file in you theme / child theme with the following code then create a new page and select the tempalte file in the page attributeAdd this code to the function.php theme file
Javascript file code: