WordPress.org

Ready to get started?Download WordPress

Forums

Use cookie to let user change page format (4 posts)

  1. ericr23
    Member
    Posted 6 years ago #

    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

  2. Michael Fields
    Themer
    Posted 6 years ago #

    Thats pretty neat!
    Great Idea.

  3. cryonics
    Member
    Posted 6 years ago #

    I was thinking to do something as that for my site.
    Thanks!

  4. toto
    Member
    Posted 5 years ago #

    Pleace Help. I have: Parse error: syntax error, unexpected '}' in...

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags