代码:
add_action( 'rest_api_init', function () {
register_rest_route( 'myapi/v1', '/top_rated_products/', [
'methods' => 'GET',
'callback' => function ($request) {
header('Content-Type: text/html; charset=UTF-8');
echo do_shortcode('[top_rated_products]');
},
'permission_callback' => '__return_true',
] );
} );
请求https://example.com/wp-json/myapi/v1/top_erated_products/显示产品列表,但只有产品图片,没有产品标题或价格。
我需要这个端点来响应渲染的 HTML 和完整的产品信息。我做错了什么?
代码的错误部分是您使用的
do_shortcode
不处理返回的结构化数据。
下面是一个可以满足您需求的代码片段
add_action('rest_api_init', function () {
register_rest_route('myapi/v1', '/top_rated_products/', [
'methods' => 'GET',
'callback' => 'get_top_rated_products',
'permission_callback' => '__return_true',
]);
});
function get_top_rated_products($request) {
$args = array(
'post_type' => 'product',
'posts_per_page' => 10, // Adjust the number of products to fetch here
'meta_key' => '_wc_average_rating',
'orderby' => 'meta_value_num',
'order' => 'DESC',
);
$products = new WP_Query($args);
$response = array();
foreach ($products->posts as $product) {
$response[] = array(
'id' => $product->ID,
'title' => get_the_title($product->ID),
'price' => get_post_meta($product->ID, '_regular_price', true),
// Add more fields as needed (e.g., 'description', 'image', etc.)
);
}
return rest_ensure_response($response);
}