Skip to content

Instantly share code, notes, and snippets.

@lots0logs
Created February 16, 2016 21:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save lots0logs/d6e8ff16beec201eb3ec to your computer and use it in GitHub Desktop.
Save lots0logs/d6e8ff16beec201eb3ec to your computer and use it in GitHub Desktop.
WordPress :: Divi Builder :: Search Module :: Custom Post Types
<?php
function my_remove_default_et_pb_custom_search() {
remove_action( 'pre_get_posts', 'et_pb_custom_search' );
add_action( 'pre_get_posts', 'my_et_pb_custom_search' );
}
add_action( 'wp_loaded', 'my_remove_default_et_pb_custom_search' );
function my_et_pb_custom_search( $query = false ) {
if ( is_admin() || ! is_a( $query, 'WP_Query' ) || ! $query->is_search ) {
return;
}
if ( isset( $_GET['et_pb_searchform_submit'] ) ) {
$postTypes = array();
if ( ! isset($_GET['et_pb_include_posts'] ) && ! isset( $_GET['et_pb_include_pages'] ) ) $postTypes = array( 'post' );
if ( isset( $_GET['et_pb_include_pages'] ) ) $postTypes = array( 'page' );
if ( isset( $_GET['et_pb_include_posts'] ) ) $postTypes[] = 'post';
/* BEGIN Add custom post types */
$postTypes[] = 'product';
/* END Add custom post types */
$query->set( 'post_type', $postTypes );
if ( ! empty( $_GET['et_pb_search_cat'] ) ) {
$categories_array = explode( ',', $_GET['et_pb_search_cat'] );
$query->set( 'category__not_in', $categories_array );
}
if ( isset( $_GET['et-posts-count'] ) ) {
$query->set( 'posts_per_page', (int) $_GET['et-posts-count'] );
}
}
}
@lots0logs
Copy link
Author

lots0logs commented May 6, 2016

A child theme is required to properly implement this customization. If you are not currently using a child theme, you can download one using the following link:

https://www.dropbox.com/s/ut4dkjq5n7j9nkz/divi-child-theme-0.1.1.r20.zip?dl=1

Add the code snippet above to your child theme's functions.php. Add your desired CPTs where it says /* BEGIN Add custom post types */

@maxizZz
Copy link

maxizZz commented May 18, 2017

works well,

thank you

@gotjoshua
Copy link

Works well, but it broke my mega-menu (on the search result page)
https://wordpress.stackexchange.com/questions/52522/adding-meta-key-via-pre-get-posts-causes-navigation-to-disappear

I changed line 10 to include a check for $query->is_main_query():

if ( is_admin() || ! is_a( $query, 'WP_Query' ) || ! $query->is_main_query() || ! is_search() ) {

@niconectado
Copy link

niconectado commented Jun 5, 2018

Cool! Thank you very much as it worked for me. Although it doesn't search in the custom fields data. Do you know how to make it able for searching within custom fields?.

////// UPDATE

I've found this very useful explanation and snippet code for achieving what i've requested: http://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/

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