• Hi guys,

    I’m using the following code that i found on another forum post and it works fantastically well for what i’m trying to achieve. The only thing i’d like to change is to add an ‘else’ query so that the code displays something else if no posts are found. I’m not an expert in php so if anyone can help with this i’d be very grateful.

    Thanks

    https://pastebin.com/9ZM76SEf

Viewing 7 replies - 1 through 7 (of 7 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Hi,
    As you may have posts return that do not qualify for the condition, use a counter as in this example.
    https://pastebin.com/zKG5RS1z

    It starts at 0, then in the loop increment the counter, only if the post is output.
    After the loop has run through and the while statement has finished, if the counter is still 0 (false), then show the Sorry Message!

    HTH

    David

    Thread Starter paa1605

    (@paa1605)

    Thanks for the quick reply keesiemeijer.

    I tried what you suggested but it caused the dreaded white screen and must have caused an error in the code. I think it may be due to some other code i have on my page so i have pasted the entire page code over at pastebin and hopefully someone can help in resolving my issue. Thanks for your help in this matter.

    https://pastebin.com/P3zKSDrZ

    Thread Starter paa1605

    (@paa1605)

    Cheers David, i tried the code you provided and it worked! Many thanks.

    Thread Starter paa1605

    (@paa1605)

    Just a follow up question,

    Im having trouble with the if/while part of this code. It works but i get errors when i try to move it about so that ‘if’ the query returns true then it outputs a certain div, then after this div start the ‘while’ portion of the code in a separate div.

    Can anyone help in getting this code to work properly but to follow a if/while/else format so i can get the layout looking correct whether the query returns posts or not.

    Thanks.

    https://pastebin.com/5VEkfTrU

    Have a look at query posts, towards the end of this page is code for the last 30 days change this to the last seven days and you can do away with the counter and revert to standard loop function.

    Copied From the Codex:
    Return posts from the last 7 days:

    <?php
    // Create a new filtering function that will add our where clause to the query
    function filter_where( $where = '' ) {
    	// posts in the last 7 days
    	$where .= " AND post_date > '" . date('Y-m-d', strtotime('-7 days')) . "'";
    	return $where;
    }
    add_filter( 'posts_where', 'filter_where' );
    
    $query = new WP_Query( $query_string );
    ?>

    HTH

    David

    Thread Starter paa1605

    (@paa1605)

    Thanks for your help David. I’ll have a play with that code and hopefully get it sorted. Cheers

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Help needed in adding an 'else' query to some code’ is closed to new replies.