0

I basically have a site where I have several different template headers that I want to load via get_template_part.

The basic idea is when someone first visits the site, they should see a random header, and every subsequent visit, see a different random header until they have seen all headers, which in that case, it will be random.

I've tried before, but with this code, it will only load one header, and continually load only that header on every refresh.

<?php
  $order = array(1, 2, 3);
shuffle($order);

get_template_part( 'headers/feat', array_shift($order) );
    ?>

I know I most likely need to be using SESSIONS, or something cookie related. Can someone point me in the right direction? Thanks!

0

You can use setcookie() to set a cookie that contains the array of visited headers. This is a simple example to start with:

function header_cookies() {
    // Check if any cookie is set
    if(isset($_COOKIE[headers_visited])) {
        $headers = $_COOKIE[headers_visited];
        // Now add your headers to cookie and save it again. Let's remove the old one first
        unset( $_COOKIE[headers_visited] );
        // Store an array of headers here
        $header_array;
        // Now set the new cookie
        setcookie( headers_visited, $header_array, time() +3600 /* For an hour */ );
        // Return the array to use wherever you want
        return $header_array;
    } else {
        // Set all the headers into an array
        $header_array;
        // Set the cookie
        setcookie( headers_visited, $header_array, time() +3600 /* For an hour */ );
        // Return the data
        return $header_array;
    }
}
// Run header_cookies() this when WordPress loads
add_action('init','header_cookies');

Now you have set the cookie, and have the array of set headers to use in your template.

Note that you need to use implode() and explode() to work with the arrays stored in the cookie.

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.