0

My problem is quite simple: I want to show a different page each time a visitor comes to my page. There are 2 pages for now, but it could be more. I have found this code:

$rand = rand(1,2);

switch($rand){

    case 1:
        get_template_part('template1');
    break;

    case 2:
        get_template_part('template2');
    break;       
}

but I don't want template parts, I really need to make it go through 2 (or more) complete pages I can define by URL or slug. Or it could be posts as well, as long as I can make them completely different (this is for multivariate testing of completely different pages which include some user interaction I want to measure)

How can I achieve this?

2
  • Note that it will be impossible to cache this page as a result unless you do the loading in javascript on the clientside, rather than on the server. Also note that anything involving random and the database will be excessively expensive/slow – Tom J Nowell Oct 31 '17 at 22:50
  • @TomJNowell, cache is not an issue. As a matter of fact I didn't know that, but what you say is kind of an added benefit, I need to avoid cache – Rick Alvarez Oct 31 '17 at 23:26
1

You can redirect users from home page to random page with this code (paste it to your functions.php)

function my_homepage_redirect() {
    if ( is_home() || is_front_page() ){
        $page = get_posts( [
            'post_type' => 'post',
            'posts_per_page' => 1,
            'category' => 1, // your category ID
            'orderby' => 'rand',
            'fields' => 'ids'
        ] );

        if ( empty( $page ) ){
            return;
        }

        wp_redirect( get_permalink( $page[0] ) );
        exit;
    }
}
add_action( 'template_redirect', 'my_homepage_redirect' );

If you want to pick random page OR random post, you can modify the 'post_type' parameter: 'post_type' => [ 'post', 'page' ],

2
  • thank you Levi. The problem is that it cycles through all existing pages, including those I'm not testing. Is is possible to limit this to only 2 pages? or it could be posts, maybe in a category – Rick Alvarez Nov 1 '17 at 20:16
  • Sure, you can limit posts to a category, I've edited my answet above (the line with 'category' => 1 // your category ID, also change 'post_type' to 'post' in that case – Levi Dulstein Nov 1 '17 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.