I seem to not be able to understand why a) my variable is not being returned within the page and, b) why there seems to be a cookie set for each individual page.
AIM:
In a product listing, I have the option to filter results by (small numbers for this example) 5, 10, or all. When I paginate the $_COOKIE
resets to the default value, and once set is set for that page. I can alternate between page 1 and page 2 with different listings of results.
File "cookies.php" (before <!doctype html>
):
<?php $post_per_page = $_POST['post_per_page'];
if (isset($post_per_page)) {
// Store it in the cookie
setcookie('post_per_page', $post_per_page, time()+60*60*24, "/");
// And save in a variable
$postsperpage = $post_per_page;
}
// Then check existing cookies
else if (isset($_COOKIE['post_per_page'])) {
$postsperpage = $_COOKIE['post_per_page'];
}
// Finally use a default value if none was set
else {
// Default to 3 for example:
$postsperpage = 3;
}
?>
Within my taxonomy.php:
$args = array(
'post_type' => 'product',
'posts_per_page' => $postsperpage,
'paged' => $paged
);
In this the $postsperpage
is empty, not even returning the default "3" from the cookies.php
. So I have to recall the contents of cookies.php
commenting out the setcookie
line.
Markup:
<form method="post">
<button type="submit" name="post_per_page" value="5">5</button>
<button type="submit" name="post_per_page" value="10">10</button>
<button type="submit" name="post_per_page" value="-1">ALL</button>
</form>
Somehow the cookie setting has fixed itself up. But I am still confused why I have to include the cookies.php
contents into the taxonomy rather than its initial variable setting being global.
Unless these php files are being included on the same page, the $postsperpage variable doesn't exist on taxonomy.php. If that is the case, you should just retrieve the cookie value on that page like so...
$postsperpage = $_COOKIE['post_per_page'];