Skip to content

Instantly share code, notes, and snippets.

@thierrypigot
Created November 19, 2014 17:11
Show Gist options
  • Save thierrypigot/672ec85f2545409a148d to your computer and use it in GitHub Desktop.
Save thierrypigot/672ec85f2545409a148d to your computer and use it in GitHub Desktop.
Dans l'admin, étendre la recherche des Custom Post Type aux métas, en plus du titre et de la description.
<?php
/*
* Dans cet exemple mon Custom Post Type est "revendeurs"
*/
add_filter('posts_join', 'revendeurs_search_join' );
function revendeurs_search_join ($join){
global $pagenow, $wpdb;
// I want the filter only when performing a search on edit page of Custom Post Type named "revendeurs"
if ( is_admin() && $pagenow=='edit.php' && $_GET['post_type']=='revendeurs' && $_GET['s'] != '')
{
$join .='LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter( 'posts_where', 'revendeurs_search_where' );
function revendeurs_search_where( $where ){
global $pagenow, $wpdb;
// I want the filter only when performing a search on edit page of Custom Post Type named "revendeurs"
if ( is_admin() && $pagenow=='edit.php' && $_GET['post_type']=='revendeurs' && $_GET['s'] != '')
{
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_distinct', 'revendeurs_search_distinct' );
function revendeurs_search_distinct( $where ){
global $pagenow, $wpdb;
if ( is_admin() && $pagenow=='edit.php' && $_GET['post_type']=='revendeurs' && $_GET['s'] != '')
{
return "DISTINCT";
}
return $where;
}
@willybahuaud
Copy link

Et donc ça fait une recherche en like sur le contenu des metas associés au CPT "revendeur", c'est ça ?

@thierrypigot
Copy link
Author

Oui

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