WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Set a Cookie with PHP - Troubleshooting (9 posts)

  1. DesignLoud
    Member
    Posted 1 year ago #

    Hi all, first let me say, Happy New Year!

    I am trying to set a cookie in my functions.php file for extending the WooCommerce shop page. Below is what I have for setting the cookie, which does indeed set the cookie. In fact everything I have works fine until you go to the next page, then it goes back to default. I was told a cookie was the best way to handle this but I cannot seem to get the kinks worked out and after two days I figured it be best to just ask for some help.

    Here is my cookie stuff:

    // Set the cookie
    function set_results_per_page_cookie() {
        if (!isset($_COOKIE['sitename_newvisitor'])) {
            setcookie('shop_pageResults', 1, time()+1209600, '/', 'tacticalminutemen.com', false);
        }
    }
    add_action( 'init', 'set_results_per_page_cookie');
    
    function dl_sort_by_page() {
    global $dl_page_value;
      $dl_page_value = $_POST['woocommerce-sort-by-columns'];
    
      if (isset($_COOKIE['shop_pageResults'])) {
         return $dl_page_value;
    }
    else {
    
    }
    
    }

    And just so you know whats up, I want to add what I have to that section in full, the point is for the user to select the number of results shown per page, problem is when you go to the next page is defaults.

    So here is the whole thing in case someone see's where I am going wrong.

    // Set the cookie
    function set_results_per_page_cookie() {
        if (!isset($_COOKIE['sitename_newvisitor'])) {
            setcookie('shop_pageResults', 1, time()+1209600, '/', 'tacticalminutemen.com', false);
        }
    }
    add_action( 'init', 'set_results_per_page_cookie');
    
    function woocommerce_catalog_page_ordering() {
    ?>
    <form action="" method="POST" name="results">
    <select name="woocommerce-sort-by-columns" id="woocommerce-sort-by-columns" class="sortby">
    <?php
    			$shopCatalog_orderby = apply_filters('woocommerce_sortby_page', array(
    			    ''       => __('Results per page', 'woocommerce'),
    				'4' 	=> __('4 per page', 'woocommerce'),
    				'12' 		=> __('12 per page', 'woocommerce'),
    				'24' 		=> __('24 per page', 'woocommerce'),
    			));
    
    			foreach ( $shopCatalog_orderby as $sort_id => $sort_name )
    				echo '<option value="' . $sort_id . '" ' . selected( $_SESSION['sortby'], $sort_id, false ) . '>' . $sort_name . '</option>';
    		?>
    </select>
    <input name="submitbutton" type="submit" value="submit" />
    </form>
    <?php
    
    } 
    
    function dl_sort_by_page() {
    global $dl_page_value;
      $dl_page_value = $_POST['woocommerce-sort-by-columns'];
    
      if (isset($_COOKIE['shop_pageResults'])) {
         return $dl_page_value;
    }
    else {
    
    }
    
    }
    
    add_filter('loop_shop_per_page','dl_sort_by_page');
    add_action( 'woocommerce_pagination', 'woocommerce_catalog_page_ordering', 20 );

    Thanks again for your help

  2. jibbius
    Member
    Posted 1 year ago #

    you have an error in line 3.

    the cookie in line 3 'newvisitor' never being set anywhere (i think)
    you will always overwrite your pageresults cookie.

  3. bcworkz
    Member
    Posted 1 year ago #

    DesignLoud, sorry you're still struggling with this. jibbius makes a valid point, but I would take that further to believe the presence of a new visitor cookie is superfluous anyway. You appear to be using the page results cookies as a flag indicating whether to use the global page value or not. This is not a good approach.

    When a new page is requested, the global page value is unlikely to have a valid value. It is global for a particular process, not for all page requests. I think we can just focus on the dl_sort_by_page filter function. This can be entered with 3 possible states the way I see it.

    1. User submitted the results per page form. We should set a cookie here to store the value the user submitted, as well as returning it so woocommerce can adjust the page.

    2. User did not submit a form, filter fired through some other woocommerce mechanism. There is however a cookie stored from a previous form submit. We should return the value we get from the cookie.

    3. User did not submit a form, filter fired through some other woocommerce mechanism. There is also no cookie stored. There is nothing to do, just return. (Sometimes in this case, we should return the value we were passed initially. Depends on how the filter was initiated with apply_filters(). You can also return a default value here.) This case will either be a new user, or a returning one who accepts the default, or does not accept cookies. Not accepting cookies is essentially the same as accepting defaults.

    Incorporate this logic into an if/elseif/else structure and you should have it :) Assuming the filter works the way I think.

  4. DesignLoud
    Member
    Posted 1 year ago #

    Thanks so much dude, I will give it a shot and let you know..

    You rock!

  5. DesignLoud
    Member
    Posted 1 year ago #

    Lol, I am sorry guys I still cannot get this even with trying to incorporate bcworkz's logic. Chances are I am doing it wrong or over-thinking it. Is it possible to get an example or is this method easier: https://github.com/carhartl/jquery-cookie. Problem with that though is that I dont know how to setup the custom jquery on my end. I tried tampering with both approaches for awhile and no success.

  6. bcworkz
    Member
    Posted 1 year ago #

    Dude you must completely frustrated with this, I feel for ya.

    I don't know if my suggestions below will work because I don't have any idea when these hooks fire. In particular the setcookiie() must run before any page content because it is sent with headers(). I don't think you want to get involved with jQuery unless things are looking desperate.

    I know... it's desperate, but hang tough for a bit. First get rid of set_results_per_page_cookie() and the 'init' hook, since we can't pass a value here easily, it's not much help, but keep in you back pocket just in case.

    The dl_sort_by_page() should be something like this:(the hooks to this are OK as is)

    function dl_sort_by_page($count) {
      if (isset($_COOKIE['shop_pageResults'])) { // if normal page load with cookie
         $count = $_COOKIE['shop_pageResults'];
      }
      if (isset($_POST['woocommerce-sort-by-columns'])) { //if form submitted
        setcookie('shop_pageResults', $_POST['woocommerce-sort-by-columns'], time()+1209600, '/', 'tacticalminutemen.com', false); //this will fail if any part of page has been output- hope this works!
        $count = $_POST['woocommerce-sort-by-columns'];
      }
      // else normal page load and no cookie
      return $count;
    }

    If the cookie fails to set here, the setcookie() line will need to be moved to whatever page template the form displays on, close to the top where no content, not even <html>, has been output yet. Also copy (not move!) the enclosing if(isset()) structure, but not the $count = line. Everything else should work properly. Good luck!

  7. DesignLoud
    Member
    Posted 1 year ago #

    You sir, are a god and a very well respected individual! I see now what you meant with the cookie and the if/elseif/else statement. Thank you very much for your help through this whole thing.

  8. DesignLoud
    Member
    Posted 1 year ago #

    Any reason why this may not be working on a mac? Cookies are enabled but they still say it doesnt work??

  9. bcworkz
    Member
    Posted 1 year ago #

    If it works in one browser, it'll work in all browsers, right? ;)

    Seriously though, the code logic must work the same for any client, it can't tell the difference (at least in this case). The only variable is what the client does with the data/cookie. I really have no idea, my best guess is the browser isn't sending the cookie data for some reason. You'll possibly need a mac that demonstrates the same behavior to track down the issue. Sorry I'm not much help.

Topic Closed

This topic has been closed to new replies.

About this Topic