skip to Main Content
<?php if ( isset( $_GET['s'] ) ) : ?>
    <h2 class="black">
    <?php
    echo sprintf( __( '%s Search Results for ', 'html5blank' ), $wp_query->found_posts );
    echo get_search_query();
    ?>
    </h2>
<?php elseif ( isset( $_GET['s'] ) == null ) : ?>
    <h2 class="red">
    <?php
    echo sprintf( __( '%s Search Results for ', 'html5blank' ), $wp_query->found_posts );
    echo get_search_query();
    ?>
    </h2>
<?php else : ?>
    <h2 class="empty">Search <?php echo get_theme_mod( 'theme_options_name', '' ); ?></h2>
<?php endif ?>

I cant get the elseif to turn red when no results are returned.

www.site.com/?s=hello

the first is a search that returns posts, this is black
the second is a search that returns no posts, this should be red
the third is an empty search, this is black.

2

Answers


  1. Please use like below code:

    <?php if(isset($_GET['s']) && $_GET['s'] !=''): ?>
        <h2 class='black'> <?php echoe sprintf(__("%s Search Results for ',
         'html5blank'), $wp_query->found_posts ); echo get_search_query(); ?> <h2>
    **<?php elseif(isset($_GET['s']) && $_GET['s'] ==''): ?>
        <h2 class='red'> <?php echoe sprintf(__("%s Search Results for ',
         'html5blank'), $wp_query->found_posts ); echo get_search_query(); ?> <h2>**
    <?php else: ?>
        <h2 class='empty'> Search <?php get_theme_mod('theme_options_name', ''); ?> </h2>
    <?php endif ?>
    
    Login or Signup to reply.
  2. First of all, you have a lot of mistakes/typos in your code.

    1. echo is echoe
    2. __() function starting with double quotes __(" but ending with single quote ')
    3. closing </h2> is wrong in the first two cases.

    after fixing all those things, the code with your expected results will be like this:

    <?php
    global $wp_query;
    
    // Check is ?s is available in url and it's value is not empty.
    if ( isset( $_GET['s'] ) && ! empty( $_GET['s'] ) ) {
    
        // check if don't have empty results.
        if ( ! empty( $wp_query->found_posts ) ) {
            ?>
            <h2 class="black"><?php echo esc_html( sprintf( __( '%1$s Search results found for %2$s', 'text-domain' ), $wp_query->found_posts, get_search_query() ) ); ?></h2>
            <?php
        } else {
            // if we have empty result.
            ?>
            <h2 class="red"><?php echo esc_html( sprintf( __( '%1$s Search results found for %2$s', 'text-domain' ), $wp_query->found_posts, get_search_query() ) ); ?></h2>
            <?php
        }
    } else {
        // if ?s exists but empty.
        ?>
        <h2 class="empty"><?php echo esc_html( sprintf( __( 'Search %s', 'text-domain' ), get_theme_mod( 'theme_options_name', '' ) ) ); ?></h2>
        <?php
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search