微信咨询

微信咨询

13610*910*9

服务热线 7*24小时

电话咨询

WordPress修改新增WP REST API接口

iamdu2022-04-18 20:25:27 浏览: 588253

今天制作小程序的时候,需要调取WP的随机文章数据,默认的WP REST API获取的随机文章不符合要求,于是自己新增了个函数获取。直接上代码。在WP对应的模板主题文件包下找到functions.php



在functions.php 最后加上

//https://[域名]/wp-json/oknnn/v1/randon   #######获取随机文章
add_action( 'rest_api_init', function () {
	register_rest_route( 'oknnn/v1', '/randon', array(
		'methods' => 'GET',
		'callback' => 'brain1981_get_single_post2',
	) );
});
function brain1981_get_single_post2(){

    global $wpdb;
    $sql = "SELECT ID, post_title,post_content,guid
            FROM $wpdb->posts
            WHERE post_status = 'publish' ";
    $sql .= "AND post_title != '' ";
    $sql .= "AND post_password ='' ";
    $sql .= "AND post_type = 'post' ";
    $sql .= "ORDER BY RAND() LIMIT 0 , 10 "; //每次返回10条数据
    $randposts = $wpdb->get_results($sql);
    $output = '';
	

    $output =array();

        foreach ($randposts as $randpost) {
			$full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($randpost->ID), 'full');
            $output[] = [
                'id'=>$randpost->ID,
				'title'=>$randpost->post_title,
				'content'=>$randpost->post_content,
                'thumbnailurl'=>$full_image_url[0],
				
            ];
        }
	$data = ['code'=>200, 'data'=>$output];
	echo json_encode($data);
	
}

小程序里就可以正常获取到随机数据了(我默认只测试返回一篇)