• Hi,

    I have this custom post type and pages, they both have the same categories although the pages and posts have certain terms selected.

    Now when I order it by rand and it happens to be that the category filters out one category that contains only one post, it seems to randomize it so that you get the one post and an empty post. Which is not what I want, i’d want to show one post at all times and that it only orderby’s when there’s more than one post.

    Here’s what my code looks like:

    global $post;
    
    $posts = get_posts(array(
        'posts_per_page'   => 1,
        'orderby'          => 'rand',
        'post_type'        => 'image',
        'post_status'      => 'publish'
    ));
    
    $terms_img = get_the_terms( $post->ID, 'image_cat' );
    
    if( $posts ):
      foreach($posts as $post):
    
        $term = array_pop($terms_img);
        $img_link = get_field('img_link');
    
          if( has_term($term, 'image_cat')){
             echo $img_link;
          }
      endforeach;
    endif;
  • The topic ‘Order by Rand and empty posts?’ is closed to new replies.