WordPress function to list site cookies

Having recently reviewed the WordPress plugins that are available to assist with the current cookie legislation I was dismayed to find a lack of anything simple that would be list out the shortcodes on a site, yet provide some flexibility.

So, I’ve written something.

Add the code below to the functions.php file in your theme folder and then use the following shortcode in a post or page…

[cookies]

Simple, eh? This will list all the site’s cookies along with their values. Two further options are available…

[cookies novalue]

This will now output the cookie values.

[cookies] ==> [/cookies]

By providing a value between opening and closing shortcodes you can override the text that is used to separate the cookie name and the value.

<?php
function get_cookies( $paras = '', $content = '' ) {
if ( strtolower( $paras[ 0 ] ) == 'novalue' ) { $novalue = true; } else { $novalue = false; }
if ( $content == '' ) { $seperator = ' : '; } else { $seperator = $content; }
$cookie = $_COOKIE;
ksort( $cookie );
$content = "<ul>n";
foreach ( $cookie as $key => $val ) {
$content .= '<li>' . $key;
if ( !$novalue ) { $content .= $seperator . $val; }
$content .= "</li>n";
}
$content .= "</ul>n";
return do_shortcode( $content );
}
add_shortcode( 'cookies', 'get_cookies' );
?>
view raw functions.php hosted with ❤ by GitHub

6 responses

  1. Thank you, David!

    That’s exactly what I was looking for.

  2. Thank you, you are a star. Was looking for exactly this and could not find it anywhere.

  3. Hello, I’ve tried the script but it shows only 3 cookies of the 8 (I’m logged in)

  4. […] none of them take your fancy I’ve written my own script which you can add to your own site for […]

  5. Thanks – some re-coding to sort out a small bug

    /**
    * Display a list of cookies on WordPress
    *
    * @param string $atts – attributes
    * @param string $content
    * @return string
    */
    function get_cookies( $atts = ”, $content = ” ) {
    $atts = shortcode_atts(
    array(
    ‘novalue’ => 0, //0 – false, 1 – true
    ‘separator’ => ‘ : ‘
    ),
    $atts
    );
    $cookie = $_COOKIE;
    ksort( $cookie );
    $out = ”;
    foreach ( $cookie as $key => $val ) {
    $out .= ” . $key;
    $out .= !$atts[‘novalue’]? $atts[‘separator’] . $val: ”;
    $out .= ”;
    }
    $out .= ”;
    return $out;
    }
    add_shortcode( ‘cookies’, ‘get_cookies’ );

    1. The above code throws a syntax error: unexpected ” : “, expected ” )”. I have no idea what this means, I don’t understand php coding. Good thing I had a backup of the functions.php, it broke my site.

Talk to me!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: