zeshan-a
10/27/2017 - 7:37 PM

Random Posts via AJAX. Use this function to get the random posts in a AJAX callback handler.

Random Posts via AJAX. Use this function to get the random posts in a AJAX callback handler.

<?php // don't include this line.

/**
 * Random Posts
 * @param  integer $count describe how many random posts you would want to fetch. 
 * @return string         HTML of the returned posts.
 */
function za_random_related_posts( $count = 3 ) {
    global $global_exclude_post_ids;

    $html = '';

    $exclude_post_id = array();
    $related_articles = array();

    if ( ! empty( $global_exclude_post_ids ) ) {
        $exclude_post_id = array_merge( $exclude_post_id, $global_exclude_post_ids );
    }

    $all_posts_args = array(
        'post_type'      => 'post',
        'posts_per_page' => -1,
        'post_status'    => array('publish'),
        'meta_query'     => array(
            array(
                'key' => '_thumbnail_id'
            )
        )
    );

    if ( ! empty( $exclude_post_id ) ) {
        $all_posts_args['post__not_in'] = $exclude_post_id;
    }

    $all_posts = get_posts( $all_posts_args );

    // Pick 3 random posts from $all_posts
    if ( ! empty( $all_posts ) && is_array( $all_posts ) ) {
        $related_articles_ids = array_rand( $all_posts, $count );

        if ( ! empty( $related_articles_ids ) && is_array( $related_articles_ids ) ) {
            foreach ( $related_articles_ids as $related_articles_id ) {
                if ( $all_posts[$related_articles_id] ) {
                    $related_articles[$related_articles_id] = $all_posts[$related_articles_id];
                }
            }
        }
        
    }

    if ( ! empty( $related_articles ) && is_array( $related_articles ) ):
        $html .= '<ul class="recent-posts">';
        // Fill $html var with data
        ob_start();
        foreach ( $related_articles as $related_article ): 
            $global_exclude_post_ids[] = $related_article->ID;
            ?>
            <li id="related-post-<?php echo $related_article->ID; ?>">
                <a href="<?php echo get_permalink( $related_article->ID ); ?>">
                    <?php if ( has_post_thumbnail( $related_article->ID ) ): ?>
                        <div class="thumb">
                            <?php echo get_the_post_thumbnail( $related_article->ID, 'related_thumb', array( 'alt' => get_the_title( $related_article->ID ) ) ); ?>
                        </div>
                    <?php endif; ?>
                    <h4><?php echo get_the_title( $related_article->ID ); ?></h4>
                </a>
            </li>
            <?php
        endforeach;
        $html .= ob_get_clean();
        $html .= '</ul>';
    endif;

    return $html;
}