0

I would like to create a very simple search tool that works independently of the regular search.

The concept is simple, search all titles of a particular post type for an EXACT match, if it finds a match go straight to the post. If not, return no match found.

I'm sure this is incredibly simple but I'm struggling. I've tried to loop through the results of $wp_query if is_search() is true, but that relies on the existing search tool and I really want them separate.

1

It is actually pretty annoying to bend WP_Query for it. However there is convenient get_page_by_title() function that can do just that. Despite the name it allows you to pass other post types as third argument.

0

That sent me in the right direction. Here is what I have came up with. I decided to create a shortcode so I can drop this anywhere needed. Using the get_page_by_title() also allowed me to find posts even if their post type was hidden from the traditional search.

function esm_search($atts) {
        extract(shortcode_atts(array(
                "label_codeword" => 'Codeword',
                "label_submit" => 'Submit'
        ), $atts));

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $error = false;
                foreach ($_POST as $field => $value) {
                        if (get_magic_quotes_gpc()) {
                                $value = stripslashes($value);
                        }
                        $form_data[$field] = strip_tags($value);
                }

                if( $form_data['codeword'] != "") {
                        $esmID = get_page_by_title($form_data['codeword'],"","esm" );
                        if( $esmID ) {
                                wp_redirect( get_permalink( $esmID ) );
                        }else{
                                $result = 'That codeword doesn\'t exist.';
                        }

                }else{
                        $result = "Please enter a codeword.";
                }
        }

        if( $result != "" ) {
                $info = '<div class="info">'.$result.'</div>';
        }

        $esm_form = '<form method="post" action="'.get_permalink().'">
                <div>
                        <input type="text" name="codeword" id="esm_codeword" size="6" maxlength="6" value="'.$form_data['codeword'].'" />
                </div>
                <div>
                        <input type="submit" value="Sumbit" name="send" id="esm_send" />
                </div>
        </form>';

        if($sent == true) {
                return $info;
        } else {
                return $info.$esm_form;
        }
}

P.S. I used this tutorial as a template for the code.

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.