Skip to content

Instantly share code, notes, and snippets.

@mebusw
Last active May 13, 2022 09:00
Show Gist options
  • Save mebusw/f2bd49db7332194538a285ca37d8308e to your computer and use it in GitHub Desktop.
Save mebusw/f2bd49db7332194538a285ca37d8308e to your computer and use it in GitHub Desktop.
loop posts of wordpress into json array
<?php //get_header(); ?>
<?php header('Content-type: text/json; charset=utf-8'); ?>
<?php
/*
$jarr=array(
'total' => 239,
'list' => array(
array(
'code'=>'001',
'name'=>'中国',
'addr'=>'Address 11',
'col4'=>'col4 data'
),
array(
'code'=>'002',
'name'=>'Name 2',
'addr'=>'Address 12',
'col4'=>'col4 data'
),
)
);
*/
$jarr=array();
?>
<?php // Loops of WordPress, see https://digwp.com/2011/05/loops/ ?>
<?php
$showposts = isset($_GET["showposts"]) ? $_GET["showposts"] : 7; // default to fetch seven posts
$custom_query = new WP_Query('cat=4&showposts='.$showposts); // cat=-9 means exclude category 9
while($custom_query->have_posts()) :
$custom_query->the_post();
global $post;
$jarr[]=array('id'=>$post->ID,'title'=>$post->post_title,'excerpt'=>$post->post_excerpt,'permalink'=>get_permalink($post));
?>
<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
<?php
//echo 'Now: '. date('Y-m-d H:i:s') ."\n";
echo $str=json_encode($jarr);
?>
<?php //get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment