Creating a Search Results Shortcode in WordPress

In WordPress, shortcodes easily add custom functionality and layout to your pages and posts. One example of this is creating a search results shortcode that displays search results in a clean and organized manner on your site. In this tutorial, we will show you how to create a search results shortcode using PHP.

Here is the code for the search results shortcode function:

<?php
function search_results_shortcode() {
    ob_start();
    if ( have_posts() ) {
        echo '<ul>';
        while ( have_posts() ) {
            the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        echo '</ul>';
    } else {
        echo 'No search results found.';
    }
    return ob_get_clean();
}
add_shortcode( 'search_results', 'search_results_shortcode' );
?>

This code creates a function called “search_results_shortcode” that checks if there are any search results. If there are, it makes an unordered list of links to the search results, with each link displaying the post’s title. If there are no search results, the function returns the message “No search results found.” The process is then added as a shortcode for post and page content using the code “[-search_results-].” Just remove this symbol “-” from shortcode.

You can add this code to your WordPress theme’s functions.php file and use the shortcode [search_results] in your search page template to display the search results cleanly and organized.

In summary, Shortcodes in WordPress are a great way to add custom functionality to your website withoutwritinge complex code. By creating a custom search results shortcode, you can display search results in a clean and organized manner on your site, providing a better user experience for your visitors.

Was this guide helpful?
YesNo