我想显示带有rest API的热门帖子,但我不知道如何使大多数人查看该帖子。
我使用update_post_meta
并像下面的代码那样获取溃败。
<?php
function post_view_count() {
if ( is_single() ) {
$count = get_post_meta( get_the_ID(), 'post_view_count', true ) ?: 0;
if ( ! $count ) {
$count = 1; // if the meta value isn't set, use 1 as a default
}
$count++;
update_post_meta( get_the_ID(), 'post_view_count', $count );
}
}
add_action( 'wp_head', 'post_view_count' );
?>
<?php
// Register a REST route
add_action( 'rest_api_init', function () {
//Path to meta query route
register_rest_route( 'popular/v2', '/pp/', array(
'methods' => 'GET',
'callback' => 'custom_meta_query_dinhmenh'
) );
});
// Do the actual query and return the data
function custom_meta_query_dinhmenh(){
// Set the arguments based on our get parameters
$args = array (
array(
'relation' => $_GET['meta_query'][0]['relation'],
'key' => $_GET['meta_query'][0]['key'],
'value' => $_GET['meta_query'][0]['value'],
'show_in_rest' => true,
//'compare' => '=',
),
);
// Run a custom query
$meta_query = new WP_Query($args);
if($meta_query->have_posts()) {
//Define and empty array
$data = array();
// Store each post's title in the array
while($meta_query->have_posts()) {
$meta_query->the_post();
$data[] = get_the_title();
}
// Return the data
return $data;
} else {
// If there is no post
return 'No post to show';
}
}
?>
您能帮我根据post_view_count
非常感谢您。