X

Créer plusieurs modèles de recherche pour les types d’articles personnalisés

Snippets by IsItWP

Vous cherchez un moyen de créer plusieurs modèles de recherche pour les types d’articles personnalisés ? Bien qu’il existe probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour créer plusieurs modèles de recherche pour les types d’articles personnalisés dans WordPress.

Instructions :

Modèle de recherche

Créez un nouveau fichier appelé search.php et ajoutez le modèle de recherche suivant. Remplacez $search_refer= CUSTOM_POST_TYPE par les noms de vos types de messages. Vous devrez également modifier le chemin du modèle pour qu’il corresponde au modèle que vous souhaitez utiliser pour afficher les résultats.

<?
/* Template Name: Search Results */

$search_refer = $_GET["post_type"];
if ($search_refer == 'CUSTOM_POST_TYPE') { load_template(TEMPLATEPATH . '/template_one-name.php'); }
elseif ($search_refer == 'CUSTOM_POST_TYPE') { load_template(TEMPLATEPATH . '/template_two-name.php'); };

?>

Afficher les résultats de la recherche

Ajoutez ce query_post juste au-dessus de la boucle dans les modèles de recherche que vous créez. N’oubliez pas de modifier le CUSTOM_POST_TYPE pour chacun de vos modèles.

<?php 
	$args = array(
		'post_type'=> 'CUSTOM_POST_TYPE',
                's'    => $s,
                'paged' => $paged,
                );
		query_posts($args);
?>

Formulaire de recherche

Ajoutez ce code HTML au modèle dans lequel vous souhaitez afficher le formulaire de recherche. Vous devrez changer le nom de CUSTOM_POST_TYPE pour le type de message que vous souhaitez rechercher. Vous devrez créer un nouveau formulaire pour chaque type d’article personnalisé ou utiliser un menu de sélection pour définir le type d'article.

<form id="searchform" action="<?php bloginfo('home'); ?>/" method="get">
	<input id="s" maxlength="150" name="s" size="20" type="text" value="" class="txt" />
	<input name="post_type" type="hidden" value="CUSTOM_POST_TYPE" />
	<input id="searchsubmit" class="btn" type="submit" value="Search" />
</form>

Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez vous référer à notre guide sur la façon d’ajouter correctement des extraits de code dans WordPress, afin de ne pas briser 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 comment créer un formulaire de contact sur WordPress.

Commentaires   laisser une réponse

  1. Sally Pilkington janvier 7, 2019 à 3:09 pm

    Hi, Thanks for this tutorial.
    I’m trying to create a custom search form to place in the sidebar of my website’s blog section. I want the search form to only look within ONLY posts (standard blog posts, not a custom post type) – and to ignore any other content, eg.pages. Is it possible to adapt this method to suit what I’m trying to do?
    I’ve had a go but with no luck.
    Many thanks

    1. Hey Sally,
      Try this tutorial on how to filter post types from search results. Hope you’ll find it helpful 🙂

  2. Purr purr purrrrfect )

  3. Perfect. Thanks!

  4. Sorry for the noob question, but is there a way to take a level further and to only search a custom meta_field within the custom post type? I’ve been searching for days and this is the closest script I could find. Right now it searches the titles and content of the post, but I’ve got a ton of custom fields for the CPT and only want to the user to search specific field. Thoughts?

  5. is it possible to adapt these instructions to search a custom taxonomy instead of a custom post? Trying to return a separate search for each custom taxonomy and I’m not quite figuring it out. Thanks!

  6. i had some syntax errors, elseif without semicolon at the end, after that all worked fine 🙂

  7. if search value is empty , example: ?s=&post_type=products it always returns me results in default template, no metter which post_type I have in search string? any fix for that?

    For example: ?s=+&post_type=products THIS WILL WORK, open in search-products.php
    this: ?s=&post_type=products WILL NOT WORK, open in search-post.php

    1. I would think your best bet would be to use javascript to require something in the field before they are able to search.

    2. I would think your best bet would be to use javascript to require something in the field before they are able to search.

    3. I would think your best bet would be to use javascript to require something in the field before they are able to search.

  8. if search value is empty , example: ?s=&post_type=products it always returns me results in default template, no metter which post_type I have in search string? any fix for that?

    For example: ?s=+&post_type=products THIS WILL WORK, open in search-products.php
    this: ?s=&post_type=products WILL NOT WORK, open in search-post.php

  9. if search value is empty , example: ?s=&post_type=products it always returns me results in default template, no metter which post_type I have in search string? any fix for that?

    For example: ?s=+&post_type=products THIS WILL WORK, open in search-products.php
    this: ?s=&post_type=products WILL NOT WORK, open in search-post.php

  10. Life saving article,thank you, i was struggling finding a good solution, this helped a lot

    1. No problem glad that we could help!

  11. Brilliant. Thank you. you ROCK!

    1. No problem glad you like the snippet!

  12. Brilliant. Thank you. you ROCK!

  13. I was using a child-theme. I had to use { load_template(get_stylesheet_directory() . ‘/template_one-name.php’); }

  14. Thanks for the tip! Works perfect…

  15. I love the idea behind this so clever.
    I do have an issue with pagination though. So renders it sorta useless unless I display all results with a ‘showposts’=>999,

    1. OH SNAP… so I had been working on this for an hour or so b4 i gave up and commented… and then i figured it out…
      Changed the query_posts arg to this

      ‘bio’,
      ‘posts_per_page’ => 10,
      ‘paged’ => $paged,
      );
      query_posts($args);
      ?>

  16. That returns to me a blank page.. Any help?

  17. Silver-monkey juin 24, 2013 à 2:06 pm

    Well done Sir. Great tip.

  18. Thanks very much! you’ve just made my morning.

  19. Is this only for custom post types?

  20. The code works fine in 3.4.2, but I had to change “post_type” to “posttype”.

    Thanks a lot! 🙂

  21. Not working for me in 3.3.1. The $s variable is possibly not getting any value. Any suggestions?

    1. Ill test things out in a recent version of wordpress just to make sure although you should not have any issues. I would also suggest updating to 3.4. Ill post back here with the results.

    2. Tested things out and appears to be working fine, did you create the custom template files and have everything setup correctly ?

  22. I get a server error trying to implement this 🙁

    1. what is the error you are getting ?

  23. alright, this is what i did for a fall-back:

    1. i created a folder within my template files called “search”. –> TEMPLATEPATH .’/search/’

    2. then created custom post templates using WordPress default search.php code.
    eg. : search-xxxxx.php where xxxxx is the custom post type.

    3. place all search-xxxxx.php custom post templates in the newly created search folder.

    4. rename default WordPress search.php to –> default-search.php

    5. create a new search.php and put the following code:

     

    6. wer’re basically calling a function called custom_search_template().

    7. lets define that function in the file fuctions.php :

    function custom_search_template() {

    $search_refer = $_GET[“post_type”];

    if ( isset($_GET[“post_type”]))
    {
        if (file_exists(TEMPLATEPATH . ‘/search/search-‘ .$search_refer. ‘.php’))
       
        load_template(TEMPLATEPATH . ‘/search/search-‘ .$search_refer. ‘.php’);
       
        else
        {
            load_template(TEMPLATEPATH . ‘/search-default.php’);
        }
    }
    else
    {
        load_template(TEMPLATEPATH . ‘/search-default.php’);
    }

    8. Finally the search form:

    <form id="searchform" action="/” method=”get”>
           

           

          
     

                Select Post Type

               
                    Business
                    News
                    LABEL
                    
              

    9. Basicaly when you use this form to submit a search querie,
       WordPress gets name=”post_type” –> ie:   $_GET[“post_type”];

    The function then checks if  $_GET[“post_type”] has been set,
     if so then loads a template file based on $search_refer = $_GET[“post_type”]
    from the /search/ folder we created.  ie. search-xxxxx.php  —>  search-$search_refer.php

    if no template called “search-$search_refer.php” exists then the function uses default-search.php to display search results.

    10. Please commemt if im mistaken.

     

  24.  function custom_search_template() {

    $search_refer = $_GET[“post_type”];

    load_template(TEMPLATEPATH . ‘/search/search-‘ .$search_refer. ‘.php’);

    }

  25. I have a problem with pagination, when custom post type search result is more than 5.

    Any advices?

    1. I tried this on the arg array

      ‘bio’,
      ‘posts_per_page’ => 10,
      ‘paged’ => $paged,
      );
      query_posts($args);
      ?>

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 !