Skip to content

Instantly share code, notes, and snippets.

@rachelmccollin
Last active May 21, 2018 21:27
Show Gist options
  • Save rachelmccollin/41344e991598d14be482039b9ed88e95 to your computer and use it in GitHub Desktop.
Save rachelmccollin/41344e991598d14be482039b9ed88e95 to your computer and use it in GitHub Desktop.
WMPU DEV display a random post from each category
<section class="random>">
<?php
$terms = get_terms( array(
'taxonomy' => 'category',
'parent' => 0
) );
$do_not_duplicate = array();
if ( $terms ) {
echo '<h3>Random Content</h3>';
echo '<ul class ="randomposts">';
foreach( $terms as $term ) {
// define the arguments
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 1,
'post__not_in' => $do_not_duplicate,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $term,
),
),
);
// run the query
$query = new WP_query ( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
echo '<li>' . $term->name . ': <a href=' . get_the_permalink() . '">' . get_the_title() . '</a></h3>';
$do_not_duplicate[] = $post->ID;
endwhile;
rewind_posts();
}
}
echo '</ul>';
}
?>
</section>
$do_not_duplicate[] = $post->ID;
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 1,
'post__not_in' => $do_not_duplicate,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $term,
),
),
);
$do_not_duplicate = array();
<?php
$terms = get_terms( array(
'taxonomy' => 'category',
'parent' => 0
) );
if ( $terms ) {
echo '<h3>Random Content</h3>';
echo '<ul class ="randomposts">';
foreach( $terms as $term ) {
}
}
?>
// run the query
$query = new WP_query ( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
echo '<li>' . $term->name . ': <a href=' . get_the_permalink() . '">' . get_the_title() . '</a></h3>';
endwhile;
rewind_posts();
}
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $term,
),
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment