0

First of all, I use Timber (TWIG) with WordPress.

I created a search query in Ajax. Everything works fine but the results do not suit me. Sometimes the results show me part of the words

Example : if I write "jour" I got "aujourd'hui" like result.

I would like to have as result only the whole words.

After doing my research here. It's indicated to use 'exact' => 1

I tried it in my query but now I no longer have any results (0 result) at each search whereas before I had the good results.

Do you have any idea about what's wrong ? Thank you.

script.js

$('#search-form').on('submit', function(e) {
    e.preventDefault();

    var searchValue = $('#search-input').val();

    if (searchValue.length > 0) {
        $.ajax({
            type: 'POST',
            url: '/wp-admin/admin-ajax.php',
            dataType: 'html',
            data: {
                'action' : 'datas_fetch',
                'terms' : searchValue
            },
            success: function(data) {
                $('#fetch-list').html(data);
            },
            error: function(data) {

            }
        });
    } else {
        $('#fetch-list').html('');
    }
});

functions.php

add_action( 'wp_ajax_nopriv_datas_fetch', 'datas_fetch' );
add_action( 'wp_ajax_datas_fetch', 'datas_fetch' );

function datas_fetch() {
    $context['page_search'] = true;
    $context['terms'] = isset($_POST['terms']) ? $_POST['terms'] : '';

    $posts_types_selected = array('pages' => 'page', 'articles' => 'post', 'videos' => 'videos', 'podcasts' => 'podcasts');

    $exclude_posts = get_field('search_exclude','option');

    if ($_POST['terms']) {
        $context['posts'] = Timber::get_posts(array(
            'post_type' => array_values($posts_types_selected),
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'paged' => 1,
            'orderby' => 'date',
            'order' => 'DESC',
            'post__not_in' => array_values($exclude_posts),
            'hide_empty' => true,
            'has_password' => FALSE,
            's' => $context['terms'],
            'exact' => 1
        ));
    } else {
        $context['posts'] = Timber::get_posts(array(
            'post_type' => array_values($posts_types_selected),
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'paged' => 1,
            'orderby' => 'date',
            'order' => 'DESC',
            'post__not_in' => array_values($exclude_posts),
            'hide_empty' => true,
            'has_password' => FALSE
        ));
    }

    Timber::render( 'bloc_fetch.twig', $context );

    die();
}

search.twig

<form role="search" id="search-form">
    <input type="text" id="search-input" class="search__input" placeholder="{{ __('Rechercher des articles, vidéos...', 'cmd') }}" value="">
    <input type="submit" id="search-submit" class="search__button" value="Rechercher">
</form>
0

Exact means exactly that - the whole field must match, not just a word in the field.

To get whole words that are part of the field, remove 'exact' => 1

Add this

if ($_POST['terms']) {
     $keyword = sanitize_text_field( $context['terms'] );
     $keyword =  '[[:<:]]' . $keyword . '[[:>:]]';
     $context['posts'] = Timber::get_posts(array(
         // other params here
         's' => $keyword,
         // etc

Suggestion: use the wp_rest_api instead of admin ajax.

  • Thank you very much for your help. I tried and unfortunately 's' => '% ' . sanitize_text_field( $context['terms'] ) . ' %', doesn't work. I always got results with "aujourd'hui" for example. Search return results only in posts. Before I had results from pages, posts and custom post typ – Jandon Oct 3 '20 at 19:41
  • Edited my answer to use regex - but it may not work with get_posts. – shanebp Oct 3 '20 at 20:06
  • Thank you again for this new solution. Unfortunately I got 0 result now. Do you think I should use something other than get_posts ? – Jandon Oct 3 '20 at 20:17
  • You could try using WP_Query directly. For whole word search, I use custom sql: $wpdb->get_col with the regex to collect the post ids and then WP_Query with post__in. I've never used Timber. – shanebp Oct 3 '20 at 20:42
  • Okay I'm interesting with this solution. I think this is because of Timber – Jandon Oct 3 '20 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.