-
-
Save tommcfarlin/4f2fa607bf002f52a7a8d1e08f75d86a to your computer and use it in GitHub Desktop.
[WordPress] Search Post Metadata in the WordaPress Admin Area
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 | |
add_filter('pre_get_posts', function ($query) { | |
// Make sure we're in the admin, an administrator, and on the edit page. | |
if (!is_admin() || !current_user_can('manage_options') || 'edit' !== get_current_screen()->base) { | |
return; | |
} | |
// Determine if the user is running a search. | |
$search = filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING); | |
if (empty($search)) { | |
return; | |
} | |
$query->set( | |
'meta_query', | |
[ | |
[ | |
'key' => 'headline_notes', | |
'value' => esc_sql(preg_replace('/\s+?/', '%', $search)), // For flexible search, make sure to replace all white space with % for LIKE. | |
'compare' => 'LIKE', | |
], | |
] | |
); | |
}); |
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 | |
add_filter( 'posts_where', function($where, $query) { | |
// Determine if 'headline_notes' appears in the WHERE clause. | |
$position = strpos($where, 'acme_meta_key'); | |
if (false === $position) { | |
return $where; | |
} | |
// Look for the 'AND' clasue and replace it with 'OR' in the WHERE clause. | |
$regularExpress = '//mi'; // Your regular expression. | |
$replacement = ''; // Your string to replace. | |
return preg_replace( | |
$regularExpression, | |
$replacement, | |
$where | |
); | |
}, 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is acme_meta_key ?