Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active February 20, 2023 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/4f2fa607bf002f52a7a8d1e08f75d86a to your computer and use it in GitHub Desktop.
Save tommcfarlin/4f2fa607bf002f52a7a8d1e08f75d86a to your computer and use it in GitHub Desktop.
[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);
@jessedmatlock
Copy link

What is acme_meta_key ?

@webdevs-pro
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment