How can I add protected content to my page? I want to protect content to only one WordPress account role – for example Subscriber. I have my own HTML CSS and JS on WordPress. So I asked Claude.ai and it told me to use this in the functions.php file in Elementor Theme files:
function check_user_status() {
$response = array(
'loggedIn' => is_user_logged_in(),
'username' => '',
'isSubscriber' => false
);
if ($response['loggedIn']) {
$current_user = wp_get_current_user();
$response['username'] = $current_user->user_login;
$response['isSubscriber'] = in_array('subscriber', $current_user->roles);
}
wp_send_json($response);
}
add_action('wp_ajax_check_user_status', 'check_user_status');
add_action('wp_ajax_nopriv_check_user_status', 'check_user_status');
And this Javascript:
let currentUser = null;
let isSubscriber = false;
function checkUserStatus() {
$.ajax({
url: wpApiSettings.ajaxUrl,
type: "POST",
data: {
action: "check_user_status",
nonce: wpApiSettings.nonce,
},
success: function (response) {
console.log("User status response:", response);
if (response.loggedIn) {
currentUser = response.username;
isSubscriber = response.isSubscriber;
} else {
currentUser = null;
isSubscriber = false;
}
updateAuthUI();
},
error: function (xhr, status, error) {
console.error("Error checking user status:", error);
},
});
}
function updateAuthUI() {
const authSection = $("#auth-section");
const userInfo = $("#user-info");
const usernameSpan = $("#username");
const subscriberContent = $("#subscriber-content");
if (currentUser) {
authSection.find("#login-button, #register-button").hide();
userInfo.show();
usernameSpan.text(currentUser);
if (isSubscriber) {
subscriberContent.show();
} else {
subscriberContent.hide();
}
} else {
authSection.find("#login-button, #register-button").show();
userInfo.hide();
subscriberContent.hide();
}
}
$(document).on("click", "#logout-button", function (e) {
e.preventDefault();
window.location.href = wpApiSettings.logoutUrl;
});
checkUserStatus();
setInterval(checkUserStatus, 60000);
document.addEventListener("DOMContentLoaded", () => {
setMealType("breakfast");
populatePopularDishes();
checkUserStatus();
});
And this HTML:
<div id="auth-section">
<button id="login-button">Zaloguj się</button>
<button id="register-button">Zarejestruj się</button>
<div id="user-info" style="display: none;">
Witaj, <span id="username"></span>!
<button id="logout-button">Wyloguj się</button>
</div>
</div>
<div id="subscriber-content" style="display: none;">
<h3>Zawartość dla subskrybentów</h3>
<p>Ta treść jest widoczna tylko dla zalogowanych subskrybentów.</p>
</div>
But it didnt worked.
Actually I want to have specific DIV restrcited to role in WordPress Accounts.
I tried like every set up ai told me and no one worked.