您的位置:首页 > 移动开发 > 微信开发

如何使用Wordpress搭建微信小程序(一)获取分页文章api

2019-01-11 11:43 597 查看

我自己写了一个Wordpress小程序,总结了一些经验在这里分享给大家。

我们想要让小程序具有实时的数据,首先第一步先要得到接口,来获取我们想要的数据。

这篇文章我们先来获取我们自定义文章类型的分页文章数据。

Wordpress自带的api查询查询出来的结果,不是我们想要的,例如https://www.pipipi.net/wp-json/wp/v2/posts/

显示的结果

默认的显示所有posts存在一个问题,即获取不到我们自定义的post type。

因此我们需要自定一个路由api,来获取我们自己想要的数据。

[code] //posts
register_rest_route('pipipi/v1','posts',array(
'methods'=>'GET',
'callback'=>function($data){
$postsResult = array(
'postInfo'=>array(),
'postsCount'=>null
);
//postInfo返回所有的文章数据
//postsCount返回查询到的所有文章,用来判断是否已经查询完毕
$offset = $data['offset'];
if(!$offset){
$offset = 0;
}
$args = array(
'post_status'=>'publish',
'post_type'=> array('diy', 'travel','code','cook','post'),
'orderby'=>'date',
'order'=>'DESC',
'posts_per_page'=>6,
'offset' => $offset
);
$args2 = array(
'post_status'=>'publish',
'post_type'=> array('diy', 'travel','code','cook','post'),
'nopaging'=>true
);
$query = new WP_Query($args);
$query2 = new WP_Query($args2);
while($query->have_posts()){
$query->the_post();
$post_id=get_the_ID();
$content = apply_filters('the_content', get_post_field('post_content', $post_id));
$like_count = get_post_meta(get_the_ID(),'suxing_ding',true);
if(!$like_count){
$like_count= '0';
}
$post_format = get_post_format($post_id);
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
$attachment_image =  wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'full')[0];
if($strResult[1]){
$images = array_slice($strResult[1],0,3);
}else{
$images = null;
}
$post_format_array = array(
'format'=>array(),
'info'=>''
);
$post_format_array['format']=$post_format;
if($post_format=='image'){
$post_format_array['info']='多图文章';
}elseif($post_format=='gallery'){
$post_format_array['info']='左图文章';
}else{
$post_format_array['info']='无图文章';
}
$date = timeago( get_gmt_from_date(get_the_time('Y-m-d G:i:s')) );
array_push($postsResult['postInfo'],array(
'title'=>get_the_title(),
'category_names'=>get_the_category(),
'post_format'=>get_post_format($post_id),
'author'=>get_the_author(),
'views'=>get_post_meta($post_id, 'views', true),
'comments_count'=>get_comments_number($post_id),
'like_count'=>$like_count,
'post_format'=>$post_format_array,
'images'=>$images,
'atachment-image'=> $attachment_image,
'default-image'=>constant("THUMB_SMALL_DEFAULT"),
'excerpt'=>get_the_excerpt(),
'date'=>$date,
'post_id'=>$post_id
));
}
$postsResult['postsCount']=$query2->post_count;
return $postsResult;
}
));

这里返回的每一个数组项,都可以定制我们想要的数据。

我这里返回了文章显示类型,特色图,还有文章前三章图片。

offset字段用来判断当前是第几页。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐