I need to retrieve data from multiple tables , wp_postmeta to get posts with a specific type ( question ) , wp_user for author informations and also wp_comments .
I need those information to use them in my rest api
I have already created a new route
add_action('rest_api_init', function () {
register_rest_route( 'myroute/v1', 'mydata/',array(
'methods' => 'GET',
'callback' => 'get_data'
));
});
function get_data($request) {
$args = array(
'post_type' => 'question',
'post_status' => 'publish',
'posts_per_page' => 8,
);
How can i join my request and get data from multiple tables
I need author's name and number of comments for every post
I need to retrieve data from multiple tables , wp_postmeta to get posts with a specific type ( question ) , wp_user for author informations and also wp_comments .
I need those information to use them in my rest api
I have already created a new route
add_action('rest_api_init', function () {
register_rest_route( 'myroute/v1', 'mydata/',array(
'methods' => 'GET',
'callback' => 'get_data'
));
});
function get_data($request) {
$args = array(
'post_type' => 'question',
'post_status' => 'publish',
'posts_per_page' => 8,
);
How can i join my request and get data from multiple tables
I need author's name and number of comments for every post
Share Improve this question asked Sep 5, 2019 at 10:05 AYMEN SOUMERAYMEN SOUMER 334 bronze badges 7 | Show 2 more comments1 Answer
Reset to default 1How can i join my request and get data from multiple tables
You don't, instead, you break it into multiple steps, and retrieve by individually
For example, lets say I want to list the top 5 posts, and display a piece of user meta about their authors, e.g. a score. That can't be done in a single call, but that's ok, so I can instead do it in several. For example:
$args = [
'posts_per_page' => 5
];
$query = new WP_query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_title(); // show the title
$score = get_user_meta( get_the_author_id(), 'score', true );
echo "Author score:" . absint( $score );
}
}
You don't need to take the user meta table and merge it into the posts table via WP_Query
, it doesn't make sense. Use the appropriate API to fetch the appropriate data, don't try and smush it all into 1 call ( it doesn't make it faster, if anything it makes it slower )
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745183322a4615519.html
WP_Query
call. Besides,WP_Query
only works for posts, for users and comments you'll need to use different functions/classes/queries. If it's just the author of thequestion
post and the number of comments, does the REST API endpoint for thequestion
post type not already provide that information? – Tom J Nowell ♦ Commented Sep 5, 2019 at 10:25