How to create a page with post from random category (2 posts)

  1. schwgmnn
    Posted 2 years ago #

    I would like to create a page that will display a random category of posts is it possible ?

    I found the solution to create a page with random posts here, but i have no idea how to change it


  2. vtxyzzy
    Posted 2 years ago #

    If you already know how to create a page of posts, you can use this code to select a random category ID to use in the query:

    // Select a random category ID
       $sql = "SELECT DISTINCT tr.term_taxonomy_id
          FROM $wpdb->term_relationships tr
          JOIN $wpdb->posts p ON (p.ID = tr.object_id)
          JOIN $wpdb->term_taxonomy tt ON (tt.term_taxonomy_id = tr.term_taxonomy_id)
          WHERE p.post_type = 'post'
          AND p.post_status = 'publish'
          AND tt.taxonomy = 'category'
          AND tt.term_taxonomy_id <> 1
          ORDER BY RAND()";
       $cat = $wpdb->get_var($sql);
       echo "CAT = $cat<br />";  // Use this for testing

Topic Closed

This topic has been closed to new replies.

About this Topic