Support » Plugins and Hacks » Use cookie to let user change page format

  • ericr23

    (@ericr23)


    This may be useful to others, and I’m sure it could be improved (I know only enough coding to solve specific challenges).

    The request from my news editor to view just the titles and categories of lots of posts at once for fast scanning over, instead of our usual index view of, say, 10 with excerpts. After trying a few things with a couple of available plugins and a second theme, here’s what I’ve come up with, requiring no extra plugins, no modifications of WP files, and no extra theme or “Pages”.

    1. Index page loads sidebar.

    2. Sidebar.php includes this code:

    <?php if (!is_single()) { ?>
    <script type="text/javascript">
    function setexcerpts() {
    document.cookie = "nwwnews=excerpts;expires=60*60";
    window.location.reload();
    }
    function setheadlines() {
    document.cookie = "nwwnews=headlines;expires=60*60";
    window.location.reload();
    }
    </script>
    <?php
    	if ($_COOKIE["nwwnews"] == "headlines") {
    	echo ('<div class=button><a href="setexcerpts()"><b><i>View with excerpts</i></b></a></div>'); }
    	else {
    	echo ('<div class=button><a href="setheadlines()"><b><i>Headlines only</i></b></a></div>'); }
    	}
    ?>

    Thus the sidebar checks if there is a browser cookie named “nwwnews” with the value “headlines”. If there is, it creates a button for viewing the page with excerpts. Otherwise (if the cookie doesn’t exist or its value isn’t “headlines”) the sidebar creates a button for viewing the page without excerpts (i.e., headlines only).

    The buttons created each calls a function to set the nwwnews cookie to, respectively, “excerpts” or “headlines” and then reload the page.

    3. The index page then uses one of two possible Loops, just like the sidebar did for its buttons:

    <?php
    if ($_COOKIE["nwwnews"] == "headlines") {
    	$posts = query_posts($query_string . '&posts_per_page=40');
    	if (have_posts()) : while (have_posts()) : the_post();
    	/*... "Headlines" Loop ...*/
    	}
    else {
    	query_posts($query_string);
    	if (have_posts()) : while (have_posts()) : the_post(); ?>
    	/*... "Excerpts" Loop ...*/
    	endif;
    }
    ?>

    Again, the second Loop is the default, and the first Loop is used only if there is an “nwwnews” cookie with the value “headlines”.

    4. See it in action at http://www.wind-watch.org/news

Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Use cookie to let user change page format’ is closed to new replies.