X

Limiter la recherche aux titres des messages

Snippets by IsItWP

Vous cherchez un moyen de limiter les résultats de votre recherche aux titres des articles ? Bien qu’il existe probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour limiter la recherche aux titres des articles dans WordPress.

Instructions:

Tout ce que vous avez à faire est d’ajouter ce code dans le fichier functions.php de votre thème ou dans un plugin spécifique à votre site:

function __search_by_title_only( $search, &$wp_query )
{
    global $wpdb;

    if ( empty( $search ) )
        return $search; // skip processing - no search term in query

    $q = $wp_query->query_vars;    
    $n = ! empty( $q['exact'] ) ? '' : '%';

    $search =
    $searchand = '';

    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }

    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() )
            $search .= " AND ($wpdb->posts.post_password = '') ";
    }

    return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez consulter notre guide sur la façon d’ajouter correctement des extraits de code dans WordPress, afin de ne pas casser accidentellement votre site.

Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 43 meilleurs thèmes de photographie pour WordPress et 11 meilleurs plugins de slider WordPress.

Commentaires   laisser une réponse

  1. Johanthan Smith janvier 6, 2023 à 4:02 pm

    anyway you can help me…. I cant get this working with DIVI THEM

  2. Hi there, thanks for this post. I was wondering if you knew how to adapt the code so it works for a custom post type, specifically, for WP Job Manager, the post type is: job_listing. Thanks.

  3. how to ingnore spaces in search

    e.g. iphone 7 32 gb
    and iphone 7 32gb

    just with a space between 32 and gb returns a big difference in results

    how we can igonre these spaces in wordpress search by adding function

    so we can get the same results from both search types

    Please advice
    Regards

  4. Your code works well on Local, not tried live yet, my php and knowledge of wordpress is not that good, I have been trying to get
    $wpdb->postmeta.page_banner_subtitle to be searched as well as post_title, to no avail, outside my scope, can someone help or point me in the right direction.
    Thank You.

  5. is this for the front end or does it also work on the backend?

    1. This is for the front end.

  6. Works great! Excellent bit of code but how would you limit the search to post title only and not page titles?

    1. Hey Richard, we’re glad you like it. The snippet is written specifically for post titles. You can see that it targets the Posts CPT.

  7. This was working well for me a month ago.
    Now I get php errors.
    Do you happen to have an updated solution?
    Its such a great bit of code for a large site.

    Warning: Parameter 2 to __search_by_title_only() expected to be a reference, value given in /wp-includes/class-wp-hook.php on line 303

    1. You could try changing line 1 to:

      function __search_by_title_only( $search, $wp_query )

  8. Why even i’m input text in search form, that limit character only 5 characters ?

    how solving it ?

  9. Thanks but Works 100% if using Chrome etc, but not well (only get half the results you should do) if using I.E (the worlds #1 browser), bizarrely !

    1. It may be I.E. is having an additional issue, as this code runs on the server and not the browser.

  10. Efekan ÇAKIR août 2, 2019 à 9:37 am

    Hi, the turkish characters and non-turkish characters are matching as a same. for example, when i search “aşk” it may gives ask, aşk. how can i fix that? i want only aşk when i search aşk. Thank you.

  11. That’s really useful – can it be adapted to search both post and page titles?

  12. This is really nice! Thank you!

  13. du lich singapore janvier 20, 2014 à 7:51 pm

    code: add_filter( ‘posts_search’, ‘__search_by_title_only’, 500, 2 );

    2 params: 500, 2 . What is mean ?

    1. 500 is the priority and 2 is the number of parameters in the callback function.

  14. du lich singapore janvier 20, 2014 à 7:46 pm

    add_filter( ‘posts_search’, ‘__search_by_title_only’, 500, 2 );
    2 params 500, 2. What is mean ?

  15. I don’t understand much of PHP, do I need to put something after and before that code?

  16. This is awesome… I’m wondering how to add this code to back-end search. I want title-wise search for wp back-end too.. 🙂

    Thank you! 🙂

  17. Hi,
    That was truly awesome.
    You just solved my problem with the least bit effort from my side.
    Thanks a lot.

  18. disqus_JuU9dzgzNc janvier 18, 2013 à 2:27 pm

    This is great! I have 2 search forms on my website. Is it possible to only apply this function to 1 of the search forms

  19. Hey Mister!
    you rule man, thanx alot

  20. Thnx Kevin … exactly the code i was looking for …

    1. Cool glad to hear I could help out.

  21. I’m new (aka “I suck”) at both PHP and WordPress.  Do I just drop this code in arbitrarily or is there a specific place where it needs to go or replace some code that’s already there?

    I put this at the bottom of the functions.php page and my screen was white, so I removed it.

    1. Ok, I was adding this to the WordPress functions.php file and not the theme one.  It works like a charm.

  22. Great code! This really cleans up the wordpress search.  Is there a way to include the first X words of the post? Maybe with the substr function?
    $content = get_the_content();
    $content = strip_tags($content);
    echo substr($content, 0, 50);

    1. In your search results template you could trim the amount of text displayed on use the excerpt template tag for a shorter result without any hacking.

  23. This is great! Something I’d like to see is a search tweak that limits the results to titles and tags. That way I have the freedom to title my posts whatever I want without worrying about needing to include keyword search terms. 

    1. Glad to hear you like the snippet! If you are going to take things that far tags, etc, I would look into the plugin “search everything” it has a lot of options that you can configure.

  24. doesn’t work! 🙁

    1. what version of wordpress are you currently running? I test everything to make sure it works before I post a snippet. Ill take a look at this again just to make sure.

      1. 3.2.1

        this is the output of $search:

        AND ( AND (((wpmtx_posts.post_title LIKE ‘%alice%’) OR
        (wpmtx_posts.post_content LIKE ‘%alice%’)) AND ((wpmtx_posts.post_title
        LIKE ‘%cooper%’) OR (wpmtx_posts.post_content LIKE ‘%cooper%’)))
        (.post_title LIKE ‘%alice%’) AND (.post_title LIKE ‘%cooper%’) OR
        (.post_title LIKE ‘%alice cooper%’))

        1. made a small update see if that fixes things,

        2. Yes! Now works! Thanks you very much!!!

      2. 3.2.1

        this is the output of $search:

        AND ( AND (((wpmtx_posts.post_title LIKE ‘%alice%’) OR
        (wpmtx_posts.post_content LIKE ‘%alice%’)) AND ((wpmtx_posts.post_title
        LIKE ‘%cooper%’) OR (wpmtx_posts.post_content LIKE ‘%cooper%’)))
        (.post_title LIKE ‘%alice%’) AND (.post_title LIKE ‘%cooper%’) OR
        (.post_title LIKE ‘%alice cooper%’))

  25. 29 Wordpress Tweaks to Improve Posts and Pages octobre 18, 2011 à 9:11 am

    […] [Source: WPSNIPP] […]

Ajouter un commentaire

Nous sommes heureux que vous ayez choisi de laisser un commentaire. N'oubliez pas que tous les commentaires sont modérés conformément à notre privacy policy, et que tous les liens sont en nofollow. N'utilisez PAS de mots-clés dans le champ du nom. Engageons une conversation personnelle et constructive.

WordPress Launch Checklist

L'ultime liste de contrôle pour le lancement de WordPress

Nous avons rassemblé tous les éléments essentiels de la liste de contrôle pour le lancement de votre prochain site Web WordPress dans un ebook pratique.
Oui, envoyez-moi le gratuit !