wordpress get posts random from specific categories

Need some help.
I have code in functions.php. when going to myweb.com/random=1 it goes to random post but I want it picks random only from chosen categories. I tried that but it still picks it from all categories.

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('category=14,17,23,28,32&orderby=rand&numberposts=1');
        foreach($posts as $post) {
            $link = get_permalink($post);
        }
        wp_redirect($link,307);
        exit;
    }
}

Related posts

2 comments

  1. Try seeing if this revised one works

    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) {
            $arguments = array('orderby' => 'rand', 'numberposts' => 1, 'category' => '14,17,23,28,32');
            $posts = get_posts( $arguments );
            foreach($posts as $post) {
                $link = get_permalink($post);
            }
            wp_redirect($link,307);
            exit;
        }
    }
    
  2. If you query some custom posts, you’ll need to do a taxonomy query instead of using category parameter – which refer to the default post type categories.

    $args = array(
        'numberposts' => 1,
        'orderby'=> 'rand',
        'tax_query' => array(
            array(
                'taxonomy' => 'category', 
                'field' => 'term_id', 
                'terms' => array(14,17,23,28,32)
            )
        )
    );
    $posts = get_post($args);
    

Comments are closed.