• Hi, I’m trying to figure out how to tweak the random post generator code to work for each of my custom post types in addition the one I have that shuffles through ALL of my custom post types. Here is the code that I have added to my functions.php file that makes it work for all 7 custom post types (articles, questions, videos, documentaries, ted-talks, memes, and music):

    add_action('init','random_add_rewrite');
    function random_add_rewrite() {
           global $wp;
           $wp->add_query_var('random');
           add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
    }
    
    add_action('template_redirect','random_template');
    function random_template() {
           if (get_query_var('random') == 1) {
                   $posts = get_posts('post_type[]=articles&post_type[]=questions&post_type[]=videos&post_type[]=documentaries&post_type[]=ted-talks&post_type[]=memes&post_type[]=music&orderby=rand&numberposts=1');
                   foreach($posts as $post) {
                           $link = get_permalink($post);
                   }
                   wp_redirect($link,307);
                   exit;
           }
    }

    And then the link that makes it work is:

    https://collectivelyconscious.net/index.php?random=1

    First of all, is it possible to add similar code to my functions.php file that works for just one of these post types using like an /index.php?random=2 link, and 3, and 4…etc? If so, how do I do it? Any help would be greatly appreciated.

Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Random Post Generator Links for Individual Custom Post Types’ is closed to new replies.