Home > Net >  Create a cookie bar consent in wordpress without plugins just pure code
Create a cookie bar consent in wordpress without plugins just pure code

Time:05-12

I am pretty new in this area but I want to create a cookie consent bar for my wordpress theme but without using plugins or any external help, just pure code(I`m using bootstrap 5.1 and php).I hope I was very explicit.Thanks in advance.

CodePudding user response:

A very basic for that will be this code

function custom_consent()
{
if(!isset($_COOKIE['consent_cookie'])):
?>
<div  id="consent-container">
    <p>We use some cookies for best use experience <a id="custom-accept" href="Javascript:void(0)">Agree</a><a id="custom-close" href="Javascript:void(0)">Close</a></p>
</div>
<?php endif; ?>
<script type="text/javascript">
(function($){

$('#custom-close').on('click', function(){
    $('#consent-container').remove();
});

$('#custom-accept').on('click', function(){

    var date = new Date();
    console.log(date.getTime());
    var expires = "";
    // this is for 1 minute, just adjust the time
    date.setTime(date.getTime()   (1*60*1000));

    expires = "; expires="   date.toUTCString();
    document.cookie = "consent_cookie=true; " expires "; path=/";
    $('#consent-container').remove();
});

})(jQuery);
</script>
<?php
}
add_action('wp_footer', 'custom_consent');
  • Related