WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. schwgmnn
    Member
    Posted 8 months ago #

    Hi!
    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

    http://www.wpbeginner.com/wp-tutorials/55-most-wanted-wordpress-tips-tricks-and-hacks/

  2. vtxyzzy
    Member
    Posted 8 months 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

Reply

You must log in to post.

About this Topic