Home > Back-end >  php if elseif else for search results, no results, empty search. I can't get the elseif to appl
php if elseif else for search results, no results, empty search. I can't get the elseif to appl

Time:09-28

<?php if(isset($_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'])==null): ?>
    <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 <?=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

CodePudding user response:

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 ><?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 ><?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 ><?php echo esc_html( sprintf( __( 'Search %s', 'text-domain' ), get_theme_mod( 'theme_options_name', '' ) ) ); ?></h2>
    <?php
}

CodePudding user response:

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 ?>
  • Related