Lets consider a scenario. We have a custom post type “Students” at the WordPress dashboard. And we have tons of single posts under this specific post type. Now we want to see if we can search any of these custom posts by its ID using the search box located at the custom post type screen.
Here is a sample screenshot for your better understanding.
In the case you don’t see the ID as per my above screenshot, you can install and activate Show Pages IDs plugin to list the IDs of each of these posts
By default, WordPress doesn’t provide any built-in functionality to search custom posts by ID. Fortunately, it’s not that complex. All you have to do is copy and paste the below code inside your theme’s functions.php
file.
Replace the custom post type slug by your own custom post type slug. Save the file and upload it back to the server. In our case, the custom post type slug is students
/**
* Add search custom posts by their ID in WordPress dashboard
*
*/
add_action( 'parse_request', 'cdxn_search_by_id' );
function cdxn_search_by_id( $wp ) {
global $pagenow;
if( !is_admin() && 'edit.php' != $pagenow && 'students' !== $_GET['post_type']) {
return;
}
// If it's not a search return
if( !isset( $wp->query_vars['s'] ) ) {
return;
}
// Validate the numeric value
$id = absint( substr( $wp->query_vars['s'], 0 ) );
if( !$id ) {
return;
}
unset( $wp->query_vars['s'] );
$wp->query_vars['p'] = $id;
}
Why should you enable search custom posts by ID?
Well, as you can see in my above screenshot, we have some students present with the same name “John Doe” but they have different IDs. So searching by name will result in a list of all students that match the name. But you just want to search for a particular student.
If you know the ID of the student, then you can easily search by ID which will result in only a single student that you exactly want.
Hope you will find this tutorial helpful.
If you would like to explore some more tips and tricks related to WordPress dashborad, please visit this page
Thank you