How to add a search function to NextGen gallery wordpress plugin

NextGen gallery is quite a nice plugin. But it lacks a function, a very obvious one… the possibility to search inside the pictures name, alternative text or description. Wouldn’t be nice if you can, with only one search query, display pictures from your gallery matching the searching terms, as well as you posts?

wp plugin nextgen gallery search

I’m not a coder. Not at all. But it still works like a charm. If you know how to edit you theme, here are the modifications you have to go through:

  1. Add this code in your file search.php (inside your template folder), right after
    <h2 class="pagetitle">Search Results</h2>
    or somewhere (depending your template) after
    <?php if (have_posts()) : ?>,
    otherwise it wouldn’t find the pictures. Pay a special attention to the line
    $nggpictures = ngg_get_search_pictures($keywords, '');
    since on the second function argument (  » ) you may indicate the number of pictures you want to display on each row result. IE, if you want to get 6 pictures displayed on each row, you have to change the line to
    $nggpictures = ngg_get_search_pictures($keywords, '6');
    By default, 4 pictures for each row are displayed. Note that you may also split the code, and put a part before and another part after the <?php while […] ?> function with the result to display pictures (if relevent) even if there is no post. That’s a bit more advanced, but people with advanced php skills won’t need any complementary explanation to achieve that.
  2. Add this code (or this code if you use NexGen 1.0) anywhere in your file functions.php (inside your template folder, create one if you don’t have any)

That’s all ! Have a look to my searchbar, and see how it works. Try with « jim lobe » or click here.

Cet article a 62 commentaires

  1. ahage4x4

    Merci bcp pr les tips pr la recherche sur les images.
    Une question, je voudrais aussi rechercher ds les TAGS des images.

    Que faut t il modifier a partir de ce code

    SELECT pid,description,alttext , ????
    FROM wp_ngg_pictures

    Cordialement

    Anthony

  2. noname

    Hello,
    Could you explain how to display pictures even if there is no relevant post? (I am not a php master- if you can simply give example code, I may be able to figure it out)

    Thanks!

  3. Laurent

    Bonjour,

    Je sais que ce n’est pas le bon endroit pour parler de cela, mais je souhaiterais vous contacter concernant la traduction du plugin « quotes collection », dont vous semblez être le traducteur « officiel ».

    J’ai remarqué que certaines expressions n’étaient pas traduites. Je les ai donc traduites et transmises à l’auteur du plugin. Je souhaiterais également vous les transmettre. Or il ne semble pas y avoir de formulaire de contact ou autre sur votre blog. Comment puis-je vous envoyer le fichier?

    Cordialement,

  4. Cerafil

    Pls Help me. Is this Search Option not available for my Theme? or why cant I get this to work?

  5. RRG

    This won’t work. No matter what I do.

    I’m assuming the following. Please help/correct if I’m wrong.

    Pasted in the themes fuctions.php the code.

    Then in the search.php (not the searchform.php)
    I pasted in after:
    the code and at the end is the:

    I have tags in my photos that are in nextgen gallery. Do a search, I get nothing.

    Thank you for reading, if I’m doing it wrong will someone please help?
    RRG

    1. RRG

      I made an adjustment, not thinking about the php code I pasted in. The below will make sense. Sorry about that!!

      This won’t work. No matter what I do.

      I’m assuming the following. Please help/correct if I’m wrong.

      Pasted in the themes fuctions.php the code.

      Then in the search.php (not the searchform.php)
      I pasted in after: « php if (have_posts()) »
      the code and at the end is the: « while (have_posts()) : the_post() »

      I have tags in my photos that are in nextgen gallery. Do a search, I get nothing.

      Thank you for reading, if I’m doing it wrong will someone please help?
      RRG

  6. Cerafil

    Still not working here and no Comments to help me.. Pls help me. Owner of this site.

  7. cerafil

    Hello? Anybody? I really want to have the same search options as this site. It is wonderfull!

  8. Cerafil

    This is it. Where should I add the code?

    <form method="get" class="searchform" action="/ »>

    <input type="text" class="text inputblur" value=" » name= »s » />

    <input name="submit" value="Search" type="image" src="/images/magnifier2-gray.gif » style= »display: block; border:none; padding: 0 0 0 5px; margin: 0; » />

  9. Cerafil

    Hi I am on AtaHualpa Theme but I cannot find my searh.php Only (Search Form.php)

    Can you point me in the right direction pls

  10. Vejito

    Hello Psyko !

    Petite question encore si jamais tu as le temps de repondre.
    J’ai enfin des resultats, mais comme certains ici les images s’affichent sur une seule colonne et ensuite quand je clique sur une image pour voir le resultat il m’affiche le jpg tout simplement sans effet d’ouverture.

    Pourrais tu m’expliquer comment arranger le code afin d’avoir les resultats sur plusieurs colonnes et comment faire pour que quand je clique sur une image il me l’ouvre comme une image de la gallerie avec le loader ?

    Merci d’avance !!!

    Vejito

  11. Yoda

    Bonjour,

    J’ai voulu mettre cette fonctionnalité (qui manque cruellement à NextGen) sur un wordpress 2.8.5 avec nextgen 1.3.6

    Lorsque je lance une recherche, j’ai l’erreur suivante :
    Fatal error: Class ‘nggallery’ not found in …./wp-content/themes/mandigo/functions.php on line 259

    Une idée du problème ?

  12. Vejito

    Bonjour Psykotik,

    J’ai suivi le tuto pour rajouter ce search, mais probleme, cela me mets des codes d’erreur en haut de ma page.

    J’ai WP 2.8.4 et Nextgen 1.3.5

    Pourrais tu m’aider dans ma demarche ? A la rigueur puis je t’envoyer le code des mes 2 pages par mail ?
    Merci d’avance pour tout reponse de ta part !

    1. jcv

      Hello Vejito,

      Est-ce que tu voudrais tout d’abord m’indiquer de quels codes d’erreur il s’agit ?

      Sinon, tu me confirmes d’avoir bien pris le second code du point 2 ?

      1. Vejito

        Bonjour !

        Alors les messages d’erreur s’affichent en haut de ma page web lorsque je mets a jour mon function.php, cela me donne sur mon index en haut :

         »
        /** ** Function to do searchs on gallery pics from NextGen Gallery plugin ** ** @keywords keywords, usually gave by the standard search query from wordpress ** @numberPicCol number of pic by row. If null, it takes 4 by default */ function ngg_get_search_pictures ($keywords, $numberPicRow = NULL) { global $wpdb; $count=1; if (!$numberPicRow) { $numberPicRow = « 4 »; } $nngquery = $wpdb->prepare(  » SELECT pid,description,alttext FROM wp_ngg_pictures WHERE MATCH (description, filename, alttext) AGAINST (%s IN BOOLEAN MODE) AND exclude != 1 « , »* ».$keywords. »* »); $pictures = $wpdb->get_results($nngquery, ARRAY_A); if ($pictures) foreach($pictures as $pic) { $out .=  »; $out .=  ».stripslashes($pic[alttext]). »; $out .= « \n »; if ($count == 0) { $out .=  »
        « ; } ++$count; $count%=$numberPicRow; } return $out; };

         »
        et mon affichage (police, taille…) s’agrandit.

        Voila le fichier search.php modifie :
        http://new.ilanmizrahi.com/search.txt

        et le fichier functions.php
        http://new.ilanmizrahi.com/functions.txt

        Merci d’avance pour ton aide 🙂

      2. Vejito

        Bonjour !

        Merci pour tes observations sur le site, Ilan est mon beau frere, et oui c’est son metier 😉

        Pour revenir a nous moutons, j’ai donc rajouter les balises php comme ceci
        http://new.ilanmizrahi.com/functions.txt

        En upgradant le fichier, j’ai un message d’erreur dans ma console d’administration :
        Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /hsphere/local/home/calibre/new.ilanmizrahi.com/web/wp-content/themes/mandigo/functions.php:243) in /hsphere/local/home/calibre/new.ilanmizrahi.com/web/wp-includes/plugin.php on line 339

        Moi pas comprendre 🙁 Encore merci pour ton temps 😉

      3. jcv

        Salut Vejito,

        D’après ce que je vois dans ton fichier functions.txt, tu as refermé le code php (par un « ?> »), mais tu ne l’as pas réouvert pour le code de recherche ajouté…

        Mets mon code entre tags php, c’est à dire fais-le précéder par un « < ? php" et finir par un "? > » (sans les guillemets et les espaces que j’ai ajoutés dans les guillemets).

        Très sympa tes photos. Très chouette site, d’ailleurs. Et si c’est ton métier, très beau métier de toute façon 🙂

      4. Vejito

        J’ai essaye le coup de la derniere chance, mais ca ne fonctionne pas, toujours ce message avec le plugin.php, je ne sais pas ce qu’il vient faire dans l’histoire celui la.

        Mais merci quand meme de ton aide, je vais chercher un autre search pour les galeries en esperant en trouver un, car j’en ai absolument besoin !

        😉

      5. Vejito

        Bon j’ai essaye avec ces codes que j’ai mis a la fin de chaque fichier.
        Je n’ai plus de message d’erreur 😀 mais je ne trouve pas de reponse 🙁

        —————————
        get(‘s’);
        $keywords = preg_replace(‘/\+/’,’ ‘,$search);
        if (function_exists (‘ngg_get_search_pictures’)) { // function from functions.php
        $nggpictures = ngg_get_search_pictures($keywords,  »); // put the number of pictures by row you want, if you don’t want « 4 »

        echo « Pictures »;
        if ($nggpictures) {
        echo $nggpictures;
        echo ‘ ‘;
        }
        else {
        echo ‘No pictures were found.’;
        }
        }
        }
        // End of NextGen Gallery search
        ?>
        ———————————

        get_results($nngquery, ARRAY_A);

        if ($pictures) foreach($pictures as $pic) {

        $out .=  »;
        $out .= ‘‘;
        $out .=  »;
        $out .= « 
        \n »;
        // pictures use float left, so don’t need the code that outputs a
        // if ($count == 0) {
        // $out .= «  »;
        // }
        // ++$count;
        // $count%=$numberPicRow;
        }
        return $out;
        };
        ?>
        —————————–

        Une tite idee ? 🙂

      6. jcv

        Ca me paraît à peu près certain que ce que tu as ajouté n’est pas en cause, puisque la ligne 243 ne contient pas de code, et que de toute façon le code ne touche pas aux headers et sessions (alors que le message d’erreur est un problèmes avec ces derniers).

        C’est donc soit le dernier include qui se passe mal (include_once(‘backend/readme.php’);) soit le fait d’ouvrir/fermer les balises qui pose problème (j’aurais jamais vu un truc pareil, mais à tout hasard, efface la fermeture et la réouverture du code php qui se suivent, en lignes 241 et 243).

        Je suis désolé, mais je ne vais pas pouvoir t’aider beaucoup plus…

      7. Vejito

        Bon,

        alors cela fonctionne d’une certaine maniere mais pas celle attendue.
        Pour que cela me donne quelquechose, j’ai change dans le code FROM wp_ngg_pictures en FROM wp_milanngg_pictures avec le nom de ma db.

        Cela me donne un resultat, MAIS s’affiche bizarrement comme sur le screen suivant :
        http://new.ilanmizrahi.com/searchpb.JPG

        Moi toujours pas comprendre, mais moi avancer 😉
        Merci de ton aide 🙂

  13. Ryd

    hi, thanks for the code before, it’s really a great help… ^,^

    by the way, i have a little problem here, not with the implementation actually (it works in some way), but with the sql query…

    it’s using full-text search function if i’m not wrong
    and from my reading so far, full-text search will not return any result (NULL) for some particular keywords (i.e. ‘the’,’a’,etc.) called ‘stopwords’, but when i try your site search function for these keywords it worked smoothly.

    i wonder how this could be done? is there any tricks behind it? as my implementation with your code (the sql query) this is somehow didn’t work unless you replace the full-text search with string function (using ‘LIKE’).

    and the last thing i can’t figure how does it work in the query, it using ‘*$keywords*’. As i know the ‘*’ operator it should be appended to the word to be affected (not prepended), so ‘*$keywords’ (without ‘*’ in the end) will be useless in my opinion (i tested it).

  14. Anonyme

    ‘There was one thing that needed fixing (‘>’ was incorrect… worked when swapped out for ‘>’) but’ in my below comment…

    the first ‘>’ was written as ‘& gt ;’ without spaces.

  15. Ok, so I used the code from reply 34’s pingback.

    There was one thing that needed fixing (‘>’ was incorrect… worked when swapped out for ‘>’) but, while I don’t know php, I got it working by comparing to an older version of the code posted previously.

    What I now need is for the search function to work via tags, rather than whatever it works by now. It’s rather necessary for me as my site is art-based and thus it kinda needs to be searchable properly.

    here is what I’m using currently for my functions:

    ## Function to do searches on gallery pics from NextGen Gallery plugin
    ##
    ## 2 vars : (1) $keywords (usually coming from the standard search query from wordpress)
    ## (2) $numberPicCol (number of pic by row, if null it takes 4 )
    function ngg_get_search_pictures ($keywords, $numberPicRow = NULL) {
    global $wpdb;
    $count=1;
    if (!$numberPicRow) { $numberPicRow = « 4 »; }

    $nngquery =  »
    SELECT pid,description,alttext
    FROM wp_ngg_pictures
    WHERE MATCH (description, filename, alttext) AGAINST (‘*$keywords*’ IN BOOLEAN MODE)
    AND exclude = ‘0’
    UNION
    SELECT pid,description,alttext
    FROM wp_ngg_pictures, wp_terms, wp_term_relationships
    WHERE pid = term_id = term_taxonomy_id and
    MATCH (name) AGAINST (‘*$keywords*’ IN BOOLEAN MODE)
    AND exclude = ‘0’
    « ;
    $pictures = $wpdb->get_results($nngquery, ARRAY_A);
    if ($pictures) foreach($pictures as $pic) {

    $out .= ‘‘;
    $out .=  »;
    $out .= « 
    n »;
    if ($count == 0) {
    $out .= «  »;
    }
    ++$count;
    $count%=$numberPicRow;
    }
    return $out;
    };

  16. digimarc

    I have been fighting with this for days now and not getting any image results back. I think I found a fix. I have adjusted it below. The important part is the $wpdb->prefix statement. Combined with the information from Flynn, I got everything working, finally!

    FROM " .$wpdb->prefix. "ngg_pictures


    /**
    ** Function to do searchs on gallery pics from NextGen Gallery plugin
    **
    ** @keywords keywords, usually gave by the standard search query from wordpress
    ** @numberPicCol number of pic by row. If null, it takes 4 by default
    */
    function ngg_get_search_pictures ($keywords, $numberPicRow = NULL) {
    global $wpdb;
    $count=1;
    if (!$numberPicRow) { $numberPicRow = "4"; }

    $nngquery = $wpdb->prepare( "
    SELECT pid,description,alttext
    FROM " .$wpdb->prefix. "ngg_pictures
    WHERE MATCH (description, filename, alttext) AGAINST (%s IN BOOLEAN MODE)
    AND exclude != 1"
    , "*".$keywords."*");
    $pictures = $wpdb->get_results($nngquery, ARRAY_A);

    if ($pictures) foreach($pictures as $pic) {

    $out .= '';
    $out .= '';
    $out .= "
    \n";

    if ($count == 0) {
    $out .= "";
    }

    ++$count;
    $count%=$numberPicRow;
    }
    return $out;
    };

  17. sarah

    AND exclude = ‘0’ wp_ngg_pictures.pid != 133
    doesn’t seem to work for me, perhaps I’m doing something wrong, however thanks for your time and your help trouble shooting

    xxxx

  18. jcv

    Hi Sarah,

    Don’t know where does you code come from, but try to add beside both
    AND exclude = ‘0′
    the line
    wp_ngg_pictures.pid != NumberYouWantExclude
    replacing « NumberYouWantExclude » by picture’s id.

  19. jcv

    Hello thanks very much for your great next gen search function.
    Is there anyway to exclude an image from the search results? I see the
    AND exclude = ‘0′
    not sure if I can use this to exclude an image ID.

    add into the function ngg_get_search_pictures part

    wp_ngg_pictures.pid != NumberYouWantExclude

    below

    AND exclude != 1

    and you’ll get what you’re looking for 🙂

  20. sarah

    Thanks so much for your reply. However I’m really bad with code. Can you let me know exactly where I need to put that. This is part of what I have already

    function ngg_get_search_pictures ($keywords, $numberPicRow = NULL) {
    global $wpdb;
    $count=1;
    if (!$numberPicRow) { $numberPicRow = « 0 »; }

    $nngquery =  »
    SELECT pid,description,alttext
    FROM wp_ngg_pictures
    WHERE MATCH (description, filename, alttext) AGAINST (‘*$keywords*’ IN BOOLEAN MODE)
    AND exclude = ‘0’
    UNION
    SELECT pid,description,alttext
    FROM wp_ngg_pictures, wp_terms, wp_term_relationships
    WHERE pid = object_id and term_id = term_taxonomy_id and
    MATCH (name) AGAINST (‘*$keywords*’ IN BOOLEAN MODE)
    AND exclude = ‘0’
    « ;

    Thanks so much

  21. sarah

    Hello thanks very much for your great next gen search function.
    Is there anyway to exclude an image from the search results? I see the
    AND exclude = ‘0’
    not sure if I can use this to exclude an image ID.

    Thanks
    Sarah

  22. Nico

    hi thnx, but i need some help, i am using Atahualpa Theme i cant find the search.php file, but i can find searchform.php with this code:

    <form method= »get » class= »searchform » action= »/ »>

    <input type= »text » class= »text inputblur » value= » » name= »s » />

    <input name= »submit » value= »Search » type= »image » src= »/images/magnifier2-gray.gif » style= »display: block; border:none; padding: 0 0 0 5px; margin: 0; » />

    Can you help me implemet this,

    Thnx y v m

  23. Artie Dugan

    Thank you SO much for this knowledge, Psykotik!! I had been desperately searching for a way to do this for months, and had almost given up. This really should be developed into a plugin!!!

    I have one small problem, and I see that two other posters have mentioned the same: the returned images are aligned in one column, one per row (there is an extra bit of space where the row break would be expected). I see from looking at Sherwood’s site that it is no longer a problem, but I have no idea how to fix on my own site.

    I’m using WordPress 2.7 and NG 1.1. Any help?

  24. monpelaud

    En faite l’affichage des images répondant au critère de recherche ne sont affichées que si au moins un article correspond lui aussi à ce critère.
    Aucune image répondant au critère n’est affichée si aucun article ne correspond à ce même critère de recherche.

  25. monpelaud

    Avec WordPress 2.7 et NextGEN Gallery 1.1.0 je n’obtiens jamais de réponse positive.

  26. annie

    Hello, this doesn’t seem to be working with 2.7 and nextgen 1.1 It always returns 0 results…any ideas?

  27. Felix

    Many many thanks for the great code – it works a treat.

    My only problem is the same as Ron had above, all of my pictures appear in one single column whatever number I put into my index.php and functions.php file… I do apologise if I’m missing something obvious!

    Cheers,
    Felix

  28. lucia

    how to add asearch function in my website in php

  29. bluerain

    I got ther error message ‘class nggallery not found’ please help me

  30. Hi Kodak:

    I had the same problem. In my case, I didn’t have the code between . This was causing the text to show up on the page, but not executing it. Putting at the end of it, fixed that problem.

  31. Kodak

    I’m using wordpress v2.7 with nextgen v1.0.2. Have implemented your code for wordpress v2.7 and nextgen v1.0.1 as in post 8 but I keep getting the following text show up and no pictures 🙁

    « if(is_search()) { $search = $wp_query->get(‘s’); $keywords = preg_replace(‘/+/’,’ ‘,$search); if (function_exists (‘ngg_get_search_pictures’)) { // function from functions.php $nggpictures = ngg_get_search_pictures($keywords, ‘3’); // put the number of pictures by row you want, if you don’t want « 4 » if ($nggpictures) { echo  »

    Pictures
    « ; echo $nggpictures; } } } »

  32. Thank you very much for this code. I have it basically working, but I’m still having a couple of problems:
    1) Regardless of whether I leave the default for number of photos per row, or put a number in the code, I get one picture per line.
    2) The search doesn’t seem to be working right. For example, I have lots of images of eagles, but if I do a search on eagle, it returns nothing. But some searches do appear to be returning results. I think it may be related to whether the images are used in a post, rather than just in the gallery. The tutorial above talked about splitting the code to display the pictures even if there are no posts. This may be related to my problem, but I’m not a good enough coder to figure out how to do what he eludes to.

    My web site is http://www.sherwoodimagery.com. The search box is in the right sidebar. Any suggestions or pointers would be greatly appreciated!

    Ron

  33. Sergei

    Hm… All working. I don’t understand there was a problem. May be in cash. Default image effect in NGG 1.0.1 is Shutter. In your code default effect Thickbox. Thanks Psykotik )

  34. tommo77funk

    hey Psykotik,

    Works great, v1.01, Thanks so much for help and quick response. Must admit whole upgrade process has put me off doing it again. If it ain’t broke don’t fix it, many many…. many thanks to you, have a great weekend, xmas and new year !

    cheers buddy 🙂

  35. jcv

    When you say it doesn’t work, do you mean it doesn’t display a picture including the word in its name or in its comment? Did you create (if it didn’t exist yet) functions.php file?

  36. Sergei

    Hmm… I put up code after and code for NexGen 1.0, but it not working in NGG 1.0.1.

  37. Sergei

    Sorry, but this code not working in wp2.7 and NGG 1.0 (

  38. tommo77funk

    Wo Hoo! Thanks so much for your reply, I really appreciate it 🙂 I’m away from home, working at the moment so wont be able to make changes till friday. I’ll let you know how I get on…

    Thanks so much 🙂 you rock !

  39. jcv

    The class « nggallery » became « ngGallery »; change it manually or download the new code.

    Enjoy!

  40. tommo77funk

    Thanks for this great tutorial, I am very grateful and I had it working on my site then this weekend I upgraded to wordpress 2.7 and next-gen v1.01 and it does not work anymore 🙁

    Any tips, advice, or help to get it working again I would be soooo grateful 🙂

    Many thanks – I hope to hear from you

  41. Body34

    Отличный сайт,я добавил его уже в закладки!!

  42. jcv

    Well, that’s quite difficult to help you with so few information… What is your WordPress version, your NextGen’s, the issue you have, and so on.

  43. Marlon

    Hi, great job on the code!! Ive followed your instructions with no luck, can you please tell me where Ive gone wrong? Can you perhaps post your entire functions and search php files, pasting the selected code simply hasn’t worked for me…

Répondre à monpelaud Annuler la réponse