• Resolved Rajarshi Bose

    (@truthsearcher83)


    In my blog index page I do not want to show posts which has empty content but only title . I am looking at ‘the_post’ hook which seems to fire inside the loop . So , I thought if the action hook is fired inside the loop I could check the post content on ‘the_post’ hook and if it is null continue with the loop . I tried the below :

    add_action('the_post' , 'rb_test_the_post');
    
    function rb_test_the_post($post){
        if (($post->post_content) == '') { 
            continue;
        }
    } 

    This gives me an error in WordPress ( “The site is experiencing technical difficulties ” and also in my code editor as it doesnt see any while or if statement for the continue statement.) . I am not able to understand why the continue statement doesnt work even though the hook is fired inside the loop .Could some one please explain?

    Also , how would one achieve this (using a plugin and not the theme as I want the empty posts not to show even when I change theme) ?

Viewing 5 replies - 1 through 5 (of 5 total)
  • You can’t continue a while loop from inside a function.
    The theme should not care what the post content is. The theme’s job is to display it.
    You can call get_the_content and check if it’s empty before output. But at least call that so that plugins can add things if needed.

    Alternatively, you can use a filter on the where clause, e.g.

    function my_filter_where($where = ''){
        return $where .= "AND trim(coalesce(post_content, '')) <>''";
    }
    add_filter('posts_where', 'my_filter_where');

    Add this code to your child themes functions.php file.

    Thread Starter Rajarshi Bose

    (@truthsearcher83)

    Thanks.

    Thread Starter Rajarshi Bose

    (@truthsearcher83)

    I had to un resolve this post . The filter ‘posts_where’ is working but I am unable to understand what “AND trim(coalesce(post_content, ”)) <>”” does even after much googling around . My SQL is not that great , I understand coalesce(post_content, ”) will return the first non-NULL character between post_content and ‘ ‘ but what does “AND trim(coalesce(post_content, ”)) <>”” actually do and what is <> for ?

    The posts_where is pretty cool and I hope to make use of it more in the future .

    Hi,

    the trim will make sure that whitespaces are removed from the start and end of the content.

    Post content with for example a space, an &nbsp; space will not be filtered out, as the post does contain a value. Trim will make sure that such posts will also be filtered.

    See also: https://www.php.net/manual/en/function.trim.php

    • This reply was modified 4 years, 8 months ago by ronaldvw.
    • This reply was modified 4 years, 8 months ago by ronaldvw.
Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Dont display post with no content’ is closed to new replies.