Samuel Elh Blog

WordPress, PHP, Python and JavaScript tutorials and snippets

How to find posts or pages containing specific keywords or text and strings in their contents

In this tutorial we will try to build a little search form and search our entire database ( actually posts table ), and return links to posts or pages found matching the subject query.

You could also use get_search_form() function of WordPress.

First off, this simple script outputs a search form asking the viewer to type a keywords, and if the keyword is set, a search will be performed looking into posts table in the database to find the ones that have a similar keyword in their contents, for example, I searched for “wordpress”, and there is a post with content as “The best CMS ever is WordPress”, this post should appear in the results snippet as it contained the word “wordpress”.

Enough bubbling, here’s the code snippet :

<?php

if ( isset( $_POST["query_submit"] ) && isset( $_POST["search_query"] ) ) {

	global $wpdb;
	$query =  mysql_real_escape_string( $_POST["search_query"] );
	$query_arr = $wpdb->get_results( 
		"
		SELECT ID,post_title
		FROM $wpdb->posts
		WHERE post_content LIKE '%$query%' AND post_status = 'publish'
		"
	);

	$count = count($query_arr);
	$plural = ( $count > 1 ) ? 's' : '';
	$html = "<p>Showing $count post$plural containing '$query' ..</p>";

	foreach ( array_filter( $query_arr ) as $q ) {
		$id = $q->ID;
		$title = ( $q->post_title == '' ) ? 'untitled' : esc_attr( $q->post_title ) ;
		$html .= "<a href="". home_url('/') ."?p=$id">$title</a><br>";
	}

	if ( $count == 0 )
		$html = "<p>No posts have matched your search query.</p>";

}

if ( isset( $_POST["query_submit"] ) && ! isset( $_POST["search_query"] ) )
	$html = "<p>Please enter a search query.</p>";

?>

<form action="" method="post">
	<h4><label for="search-query">Enter your seach term(s) below:</label></h4>
	<input type="text" name="search_query" value="<?php echo $query; ?>" id="search-query" />
	<input type="submit" name="query_submit" value="Search" />
</form>

<?php echo $html; ?>

To use this you code, you will need to wrap it in a function and then call this function with something like a shortcode, because if you just throw it in your functions file, it will caused some trouble and appear everywhere in the top of your site.

As is, the code will display a link to each post in the snippet, if you needed to display more elements like post date, author, excerpt.. – all you need is to select them in the MySQL query and add them within the foreach loop:

Select more data separating them by commas :

SELECT ID,post_title,post_content,post_date

Or everything :

SELECT *

And don’t forget to add the selected elements in the loop:

$html .= $q->post_content; // for post content

Shortcode

I will wrap the previous snippet in a function to set up a quick shortcode – add it to your child theme functions file or with a quick plugin :

function elh_search_form() {
 
 	$query = '';
 	$html = '';
    if ( isset( $_POST["query_submit"] ) && isset( $_POST["search_query"] ) ) {
 
        global $wpdb;
        $query =  mysqli_real_escape_string( $_POST["search_query"] );
        $query_arr = $wpdb->get_results( 
            "
            SELECT ID,post_title
            FROM $wpdb->posts
            WHERE post_content LIKE '%$query%' AND post_status = 'publish'
            "
        );
 
        $count = count($query_arr);
        $plural = ( $count > 1 ) ? 's' : '';
        $html = "<p>Showing $count post$plural containing '$query' ..</p>";
 
        foreach ( array_filter( $query_arr ) as $q ) {
            $id = $q->ID;
            $title = ( $q->post_title == '' ) ? 'untitled' : esc_attr( $q->post_title ) ;
            $html .= "<a href="". home_url('/') ."?p=$id">$title</a><br>";
        }
 
        if ( $count == 0 )
            $html = "<p>No posts have matched your search query.</p>";
 
    }
 
    if ( isset( $_POST["query_submit"] ) && !isset( $_POST["search_query"] ) )
        $html = "<p>Please enter a search query.</p>";
 
    ob_start();
    ?>
 
    <form action="" method="post">
        <h4><label for="search-query">Enter your seach term(s) below:</label></h4>
        <input type="text" name="search_query" value="<?php echo $query; ?>" id="search-query" />
        <input type="submit" name="query_submit" value="Search" />
    </form>
 
    <?php
    echo $html;
 
    return ob_get_clean();
 
}
add_shortcode('elh-search-form', 'elh_search_form');

Add this shortcode where you want the form to appear ( maybe in a post, page or widget ) [elh-search-form]

Little preview

Here’s a little preview of what this small code can do so far:

search posts or pages by keyword

search results for “youtube” – 1 post matched

As usual, if you had any issues or comments, feel free to drop them below !

Digital Ocean

Cheap Cloud SSD Hosting

Get a VPS now starting at $5/m, fast and perfect for WordPress and PHP applications

Sign Up with $10 Credit

1 Comment

  1. The code gives me this error:

    Parse error: syntax error, unexpected ‘”. home_url(‘/’) .”‘ (T_CONSTANT_ENCAPSED_STRING) in /var/www/vhosts/kandelaar-kopen.nl/httpdocs/wp-content/themes/news-pro/functions.php on line 148

    Line 148 corresponds to 24 in your last code snippet.

    Is it possible for you to correct this error?
    I am going crazy trying to find some outdated URLs in more than 1k of WP posts, the popular search and replace plugins do that: search and replace, while I just want to find out which posts and pages contain the urls I am interested in.

    Hope you can fix the code. Thanks.

Leave a Reply

Your email address will not be published.

*

© 2017 Samuel Elh - Powered by WordPress, DigitalOcean & NameCheap

Theme by Anders NorenUp ↑

Subscribe to our mailing list

Sign up to receive updates about WordPress, free and premium plugins and themes in general and tips and tricks

* indicates required