Created
December 6, 2019 13:36
Adding meta fields with orderby endpoint to WordPress rest API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Register the meta field for the rest api | |
// https://stackoverflow.com/questions/56460557/how-to-include-meta-fields-in-wordpress-api-post#answer-56508996 | |
add_action( 'rest_api_init', 'register_postviews_meta_fields'); | |
function register_postviews_meta_fields(){ | |
register_meta( 'post', 'wpb_post_views_count', array( | |
'type' => 'integer', | |
'description' => 'Post views', | |
'single' => true, | |
'show_in_rest' => true | |
)); | |
} | |
//https://github.com/WP-API/WP-API/issues/2308#issuecomment-262886432 | |
add_filter('rest_endpoints', function ($routes) { | |
// I'm modifying multiple types here, you won't need the loop if you're just doing posts | |
foreach (['post'] as $type) { | |
if (!($route =& $routes['/wp/v2/' . $type])) { | |
continue; | |
} | |
// Allow ordering by my meta value | |
$route[0]['args']['orderby']['enum'][] = 'meta_value_num'; | |
// Allow only the meta keys that I want | |
$route[0]['args']['meta_key'] = array( | |
'description' => 'The meta key to query.', | |
'type' => 'string', | |
'enum' => ['wpb_post_views_count'], | |
'validate_callback' => 'rest_validate_request_arg', | |
); | |
} | |
return $routes; | |
}); | |
//https://github.com/WP-API/WP-API/issues/2308#issuecomment-265875108 | |
add_filter('rest_post_query', function ($args, $request) { | |
if ($key = $request->get_param('meta_key')) { | |
$args['meta_key'] = $key; | |
} | |
return $args; | |
}, 10, 2); | |
// This enables the orderby=menu_order for Posts | |
// https://www.timrosswebdevelopment.com/wordpress-rest-api-post-order/ | |
add_filter( 'rest_post_collection_params', 'filter_add_rest_orderby_params', 10, 1 ); | |
// And this for a custom post type called 'portfolio' | |
// add_filter( 'rest_portfolio_collection_params', 'filter_add_rest_orderby_params', 10, 1 ); | |
/** | |
* Add menu_order to the list of permitted orderby values | |
*/ | |
function filter_add_rest_orderby_params( $params ) { | |
$params['orderby']['enum'][] = 'meta_value_num'; | |
return $params; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment