Created
October 27, 2017 19:37
-
-
Save zeshanshani/f456d473d7e85bffc7264c749e50fda9 to your computer and use it in GitHub Desktop.
Random Posts via AJAX. Use this function to get the random posts in a AJAX callback handler.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment