Hi Guys and thank you in advance for giving me some attention with this. I have this code in wordpress that I just can’t get right.

I have the US states in a drop-down form. When the user chooses an option from the select form and presses the “set new location” button, I need a cookie to be written , containing that location’s ID (or actual name). I am using (or at least trying to use) the jquery cookie plugin (https://github.com/carhartl/jquery-cookie) – but probably the main problem is I know almost no jQuery, lol.

The think that is not working is jQuery.cookie('my_cookie', 'my_value');

Can you help me? Here is the code I am working on:

                <form id="categoriesform" action="<?php bloginfo('url'); ?>" method="get">

                    <div>
                    <?php $cats = get_categories($args); 
                    $termID = $_COOKIE['my_cookie'];

                    $term = get_term( $termID, 'location' );

                    $name = $term->name;
                    ?>
                    <select id="categories">
                    <?php foreach ($cats as $cat) : ?>
                        <option value="<?php echo get_term_link($cat, $cat->taxonomy) ?>" ><?php echo $cat->name ?></option>
                    <?php endforeach; ?>
                    </select>
                    <input type="submit" name="submit" value="Set New Location" />
                    </div>
                </form>

                <script>

                jQuery(document).ready(function()
                {
                    jQuery('#categoriesform').submit(function()
                    {
                        jQuery.cookie('my_cookie', 'my_value');
                        window.location = jQuery('#categories').val();
                        return false;
                    });
                });
                </script>

1 Answer
1

If you don’t give the cookie an expires time it will only be available during that session. You will also need to destroy an existing cookie if it is already set.

jQuery(function() {

    jQuery('#categoriesform').submit(function(e) {
         if (jQuery.cookie('my_cookie') ) { jQuery.cookie( 'my_cookie', null) }
        jQuery.cookie('my_cookie', 'my_value', { expires: 30 });
    });
});

Have you tested to see if the cookie is being set? Use the network tab in chrome developer tools and load the page. Click on the first item on the left which will be the url of your site then click on cookies tab and see if the cookie is there.

When reading your cookie you should also check to see if it’s there.

if (isset($_COOKIE['my_cookie'])) {
$termID = $_COOKIE['my_cookie'];

Leave a Reply

Your email address will not be published. Required fields are marked *