现在不少以worldpress为后台的微信小程序都是以github上开源的守望轩提供的WordPress 版微信小程序源码为基础开发的,但是其小程序源代码和配套的插件却并没有提供获取随机文章列表 Api .所以我们如果要实现小程序获取worldpress后端的随机文章的话,就需要给插件增加功能api,并适当修改微信小程序的源码才可以实现.首先需要给wp-rest-api-for-app插件增加一个random.php.
1、把下面的代码保存为 random.php 文件。
<?php
// 定义随机文章 API
add_action( 'rest_api_init', function () {
register_rest_route( 'wxapp/v1', 'post/random', array(
'methods' => 'GET',
'callback' => 'getRandomPosts'
));
});
function getRandomPosts( $data ) {
$data=get_random_post_data(10);
if ( empty( $data ) ) {
return new WP_Error( 'noposts', 'noposts', array( 'status' => 404 ) );
}
// Create the response object
$response = new WP_REST_Response( $data );
// Add a custom status code
$response->set_status( 200 );
return $response;
}
function get_random_post_data($limit = 10) {
global $wpdb, $post;
$today=date("Y-m-d H:i:s"); // 获取当天日期时间
$limit_date=date("Y-m-d H:i:s", strtotime("-1 year")); // 获取指定日期时间
$sql="SELECT ID, post_title,post_date FROM $wpdb->posts WHERE post_status = 'publish' AND post_title != '' AND post_password ='' AND post_type = 'post' ORDER BY RAND() LIMIT 0 , $limit";
$randposts = $wpdb->get_results($sql);
$posts=array();
foreach ($randposts as $post) {
$post_id = (int) $post->ID;
$post_title = stripslashes($post->post_title);
$pageviews = (int) $post->pageviews_total;
$post_date =$post->post_date;
$post_permalink = get_permalink($post->ID);
$_data["post_id"] =$post_id;
$_data["post_title"] =$post_title;
//$_data["pageviews"] =$pageviews;
$_data["post_date"] =$post_date;
$_data["post_permalink"] =$post_permalink;
$pageviews = (int) get_post_meta( $post_id, 'wl_pageviews',true);
$_data['pageviews'] = $pageviews;$like_count = $wpdb->get_var("SELECT COUNT(1) FROM ".$wpdb->postmeta." where meta_value='like' and post_id=".$post_id);
$_data['like_count'] = $like_count;
$comment_total = $wpdb->get_var("SELECT COUNT(1) FROM ".$wpdb->comments." where comment_approved = '1' and comment_post_ID=".$post_id);
$_data['comment_total']= $comment_total;
$images =getPostImages($post->post_content,$post_id);$_data['post_thumbnail_image']=$images['post_thumbnail_image'];
$_data['content_first_image']=$images['content_first_image'];
$_data['post_medium_image_300']=$images['post_medium_image_300'];
$_data['post_thumbnail_image_624']=$images['post_thumbnail_image_624'];
$posts[] = $_data;
}
return $posts;
}
2、在插件处引用这个文件。修改 wp-rest-api-for-app.php 这个文件,在最后加上
include(WP_REST_API_FOR_APP_PLUGIN_DIR . 'random.php'); // 随机文章列表
3、修改微信小程序源码 utils 目录下的 api.js,将
else if (flag == 4) {
url += "post/praisethisyear"
修改为:
暂无评论