WordPress hwk Codes Ajouter un Argument de Recherche « LIKE » dans une WP_Query
Ajouter un Argument de Recherche “LIKE” dans une WP_Query
17 April 2018
<?php | |
add_filter('posts_where', 'hwk_wp_query_post_like', 10, 2); | |
function hwk_wp_query_post_like($where = '', &$wp_query){ | |
global $wpdb; | |
if(!$post_like = $wp_query->get('post_like')) | |
return $where; | |
if(is_string($post_like)) | |
return $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql($wpdb->esc_like($post_like)) . '%\''; | |
if(!is_array($post_like)) | |
return $where; | |
if(!isset($post_like[0]) || (!is_string($post_like[0]) && !is_array($post_like[0]))) | |
return $where; | |
$post_like = wp_parse_args($post_like, array( | |
'relation' => 'OR', | |
'column' => 'post_title', | |
)); | |
$post_title_like_array = array(); | |
$post_title_like_array[] = $post_like[0]; | |
if(is_array($post_like[0])){ | |
$post_title_like_array = array(); | |
foreach($post_like[0] as $k => $rule){ | |
$post_title_like_array[] = $rule; | |
} | |
} | |
$where_addon = array(); | |
foreach($post_title_like_array as $keyword){ | |
$where_addon[] = $wpdb->posts . '.' . $post_like['column'] . ' LIKE \'%' . esc_sql($wpdb->esc_like($keyword)) . '%\''; | |
} | |
$where .= ' AND ( ' . implode(' ' . $post_like['relation'] . ' ', $where_addon) . ' )'; | |
return $where; | |
} | |
/* | |
// Usage: | |
// Post_title like 'Contact' OR 'Informations': | |
$query = new WP_Query(array( | |
'post_type' => 'page', | |
'posts_per_page' => -1, | |
'post_like' => array( | |
'relation' => 'OR', // OR | AND – default: OR | |
'column' => 'post_title', // post_title | post_content etc… – default: post_title | |
array( | |
'Contact', | |
'Informations', | |
) | |
) | |
)); | |
// Post_title like 'Contact' AND 'Informations': | |
$query = new WP_Query(array( | |
'post_type' => 'page', | |
'posts_per_page' => -1, | |
'post_like' => array( | |
'relation' => 'AND', | |
array( | |
'Contact', | |
'Informations', | |
) | |
) | |
)); | |
// Post_title like 'Contact': | |
$query = new WP_Query(array( | |
'post_type' => 'page', | |
'posts_per_page' => -1, | |
'post_like' => 'Contact' | |
)); | |
// Post_content like 'Contact': | |
$query = new WP_Query(array( | |
'post_type' => 'page', | |
'posts_per_page' => -1, | |
'post_like' => array( | |
'column' => 'post_content', | |
array( | |
'Contact' | |
) | |
) | |
)); | |
*/ |
Plus de codes
Créer un Compte Administrateur depuis un Thème WordPress
25 June 2018
Changer le Slug de Base des Auteurs WordPress
13 May 2018
Trier une WP Query par les Noms des Termes d’une Taxonomie
8 May 2018
Convertir du JSON au Format CSV
8 May 2018
Ajouter des données dans l’objet WP_POST
5 May 2018
Enregistrer un Post Type avec Archive Uniquement, sans vue Single
25 April 2018