Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin tommcfarlin/00-pre-get-posts.php Secret
Last active Nov 7, 2019

Embed
What would you like to do?
[WordPress] Search Post Metadata in the WordaPress Admin Area
<?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',
],
]
);
});
<?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
You can’t perform that action at this time.