skip to Main Content

I am a bit stuck with the code below for my WordPress site:

<?php
    $user = wp_get_current_user();
    $allowed_roles = array('subscriber', 'visitor');
     if ( array_intersect($allowed_roles, $user->roles ) ) echo '<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXX" crossorigin="anonymous"></script>' ?>

I want the Adsense code only be shown in the HEAD section for site visitors and the user role SUBSCRIBER. I tried ‘visitor’ but that didn’t worked.

I don’t know how to apply "array_diff" in this situation to display the Adsense code in the header for SITE VISITORS and SUBSCRIBER role?

2

Answers


  1. For "subscriber" you can use function current_user_can

    For guests you can use function is_user_logged_in()

    if ( current_user_can( 'subscriber' ) || !is_user_logged_in()) {
               // echo your adsense code
    }
    
    Login or Signup to reply.
  2. If you use the Site Kit plugin by Google to insert your ad code there is an option to restrict the ads snippet to users who can write posts. Hopefully that helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search