Skip to content

Instantly share code, notes, and snippets.

@gradosevic
Last active October 14, 2021 23:18
Show Gist options
  • Save gradosevic/1d254f3676a10c7393b95bfc43c69cfa to your computer and use it in GitHub Desktop.
Save gradosevic/1d254f3676a10c7393b95bfc43c69cfa to your computer and use it in GitHub Desktop.
WordPress: Search in ACF fields, functions.php
<?php
///////////////////////////////////
/// SUPPORT FOR SEARCHING IN ACF
///////////////////////////////////
/* Join posts and post-meta tables
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*/
function cf_search_join( $join ) {
global $wpdb;
if ( is_search() ) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join' );
/**
* Modify the search query with posts_where
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
*/
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$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_where', 'cf_search_where' );
/**
* Prevent duplicates
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
*/
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
@xxxdepy
Copy link

xxxdepy commented Apr 22, 2019

When running a WP_Query for getting posts by custom fields name it is throwing this error

WordPress database error: [Not unique table/alias: 'wp_postmeta']

My Query


// args
$argschild = array(
	'numberposts'	=> 2,
	'post_type'		=> 'contactdirectory',
	'meta_key'		=> 'select_parent',
	'meta_value'	=> $parentid
);

// query
$the_query_child = new WP_Query( $argschild );

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