Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. Jany-M revised this gist Feb 4, 2021. No changes.
  2. Jany-M revised this gist Feb 4, 2021. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion wp_include_terms_in_search_wpml_compatible.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    <?php
    function custom_search_where($where){

    global $wpdb;
    @@ -47,4 +48,6 @@ function custom_search_groupby($groupby){
    add_filter('posts_where','custom_search_where');
    add_filter('posts_join', 'custom_search_join');
    add_filter('posts_groupby', 'custom_search_groupby');
    }
    }

    ?>
  3. Jany-M created this gist Feb 4, 2021.
    50 changes: 50 additions & 0 deletions wp_include_terms_in_search_wpml_compatible.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    function custom_search_where($where){

    global $wpdb;

    if (is_search() && get_search_query())
    $where .= "OR ((t.name LIKE '%".get_search_query()."%' OR t.slug LIKE '%".get_search_query()."%') AND {$wpdb->posts}.post_status = 'publish')";

    // WPML
    if (function_exists('icl_get_languages')) {
    $lang_code = 'it'; // better set a default lang code as fallback here
    if(defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE != '') {
    $lang_code = ICL_LANGUAGE_CODE;
    }
    $where .= "AND language_code = '".$lang_code."'";
    }

    return $where;
    }

    function custom_search_join($join){

    global $wpdb;
    if (is_search()&& get_search_query())
    $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id";

    return $join;
    }

    function custom_search_groupby($groupby){

    //if(is_admin()) return;

    global $wpdb;

    // we need to group on post ID
    $groupby_id = "{$wpdb->posts}.ID";
    if(!is_search() || strpos($groupby, $groupby_id) !== false || !get_search_query()) return $groupby;

    // groupby was empty, use ours
    if(!strlen(trim($groupby))) return $groupby_id;

    // wasn't empty, append ours
    return $groupby.", ".$groupby_id;
    }

    if(!is_admin()) {
    add_filter('posts_where','custom_search_where');
    add_filter('posts_join', 'custom_search_join');
    add_filter('posts_groupby', 'custom_search_groupby');
    }