0

I have this piece of code to show the author posts of the author of the current post, but I want to make an if statement, if no posts then echo out some text. I have now this but it do not work (above is the function for author posts and at the bottom is my if statement):

            <?php 

            function get_related_author_posts() {
                global $authordata, $post;

                $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post_type' => 'kenniscentrum', 'post__not_in' => array( $post->ID ), 'posts_per_page' => 5 ) );

                $output = '<ul>';
                foreach ( $authors_posts as $authors_post ) {
                    $output .= '<li><a href="' . get_permalink( $authors_post->ID ) . '">' . apply_filters( 'the_title', $authors_post->post_title, $authors_post->ID ) . '</a>' . apply_filters( 'the_excerpt', $authors_post->post_excerpt, $authors_post->ID ) . '</li>';
                }
                $output .= '</ul>';

                return $output;

            }

            /*add this hook where you need the related posts*/
            if(get_related_author_posts()) :
                echo get_related_author_posts();
            else :    
                echo 'No articles...';
            endif;  
            ?>

Can someone help me out with this?

1

Maybe this do the trick, put your if statement inside the function to check if the number of posts retrieved is >= 1, if so begin the foreach else print a message

        function get_related_author_posts() {
            global $authordata, $post;

            $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post_type' => 'kenniscentrum', 'post__not_in' => array( $post->ID ), 'posts_per_page' => 5 ) );

            if( $authors_posts && count( $authors_posts ) >= 1 ) :
            $output = '<ul>';
            foreach ( $authors_posts as $authors_post ) {
                $output .= '<li><a href="' . get_permalink( $authors_post->ID ) . '">' . apply_filters( 'the_title', $authors_post->post_title, $authors_post->ID ) . '</a>' . apply_filters( 'the_excerpt', $authors_post->post_excerpt, $authors_post->ID ) . '</li>';
            }
            $output .= '</ul>';
            else :
            $output = '<p>'. __( 'No posts found' ) .'</p>';
            endif;
            return $output;

        } 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.