How to get wordpress COOKIEPATH in jquery?

I have a wordpress site which I would like to extend with custom plugin. In my plugin I use an external custom JavaScript file.

In JavaScript file I need to retrieve the WordPress constant COOKIEPATH. But I don’t how to access it. This is what my code looks like: (The COOKIEPATH needs to be inserted where you can see COOKIEPATH in the code)

Read More
jQuery(document).ready(function($) {

    var cookie_favs = '_favorites';
        //test

    if(jQuery.cookie(cookie_favs)!==null) {
        jQuery('.actions-favorites').each(function(i, obj) {
            var the_id = jQuery( this ).('name');
                if(jQuery.cookie(cookie_favs).search(the_id)!=-1) {
                    jQuery('button[name='+the_id + ']').hide();
                    jQuery('#favoritesaction' + the_id).show();
                    jQuery('#favoritesaction' + the_id).append(' <span class="badge badge-important">' + jQuery.cookie(cookie_favs).split(',').length + '</span>');
                    //}
                }
            }
    });

    jQuery('.actions-favorites').click(function() {
                var the_id = jQuery( this ).('name');
                if(jQuery.cookie(cookie_favs)===null || jQuery.cookie(cookie_favs)=='') {                       
                    jQuery.cookie(cookie_favs, the_id ?>,{ expires: 60, path: COOKIEPATH });
                } else {
                    var fav = $.cookie(cookie_favs);
                    jQuery.cookie(cookie_favs, fav + ',' + the_id,{ expires: 60, path: COOKIEPATH });
                }
                jQuery(this).fadeOut(150, function() {
                  jQuery('.actions-favorites-link').fadeIn(150);
                  jQuery('.actions-favorites-link').append(' <span class="badge badge-important">' + jQuery.cookie(cookie_favs).split(',').length + '</span>');
                });                             
     });                    


});

Does anyone have an answer? Thank you in advance!

Related posts

Leave a Reply

1 comment

  1. In wordpress it’s simple, you localize the script with wp_localize_script to pass values from PHP to javascript.

    Inside your plugin where you’re adding the scripts, do

    wp_register_script( 'some_handle', 'path/to/myscript.js' );
    
    // Now we can localize the script with our data.
    $cookies = array( 'path' => COOKIEPATH );
    wp_localize_script( 'some_handle', 'my_global_name', $cookies );
    
    // The script can be enqueued now or later.
    wp_enqueue_script( 'some_handle' );
    

    Now inside your javascript file you have a magical global variable that you can access

    jQuery(document).ready(function($) {
    
        var cookie_favs = '_favorites';
    
        var cookie_path = my_global_name.path; // returns the cookie path
    
         ....etc