微信咨询

微信咨询

13610*910*9

服务热线 7*24小时

电话咨询

wordpress自定义路由接口 获取带特色图(缩略图)的随机文章

iamdu2021-05-28 14:38:17 浏览: 426006
//https://[域名]/wp-json/btaotao/v1/randon   #######获取随机文章
add_action( 'rest_api_init', function () {
	register_rest_route( 'btaotao/v1', '/randon', array(
		'methods' => 'GET',
		'callback' => 'suijiwenzhang',
	) );
});
function suijiwenzhang(){

    global $wpdb;
    $sql = "SELECT ID, post_title,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,
                'thumbnailurl'=>$full_image_url[0],
				
            ];
        }
	$data = ['code'=>200, 'data'=>$output];
	echo json_encode($data);
	
}