Please I need help!!!
I’m working on a WordPress site where I need to implement a feature that allows users to unhide specific content on their dashboard when they click a button on a separate services page. Here’s a brief overview of what I’m trying to achieve and the issues I’m encountering:
Objective:
On the user dashboard, certain content containers are initially hidden.
Users should be able to click a button on a services page to “add” a service, which will unhide the corresponding container on their dashboard.
The hidden container should remain visible to the user even after a page refresh or logs out and log back in.
Using WpCode –
JavaScript Functionality:
I have implemented a JavaScript function that sends an AJAX request to the server when a button is clicked. The request aims to update the user meta data to indicate that the service should be visible.
jQuery(document).ready(function($) {
$('.unhide-service-btn').on('click', function(e) {
e.preventDefault();
var serviceId = $(this).data('service-id');
$.ajax({
url: my_ajax_object.ajax_url,
type: 'POST',
data: {
action: 'unhide_service',
serviceId: serviceId,
nonce: my_ajax_object.nonce
},
success: function(response) {
console.log('Response:', response);
if (response.success) {
$('#service-' + serviceId).removeClass('hidden-service');
}
},
error: function(xhr, status, error) {
console.log('Error:', status, error);
}
});
});
});
Also using WpCode
PHP Backend Handling:
I’ve set up an AJAX handler in PHP to process the request and update the user meta data. The handler checks the nonce for security.
Enqueue Script:
I’m enqueueing the JavaScript file and localizing it to pass AJAX URL and nonce.
function enqueue_custom_scripts() {
wp_enqueue_script('custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), null, true);
wp_localize_script('custom-js', 'my_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('unhide_service_nonce') // Add nonce
));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
function unhide_service_callback() {
// Check nonce for security
check_ajax_referer('unhide_service_nonce', 'nonce');
// Retrieve and process AJAX data
$service_id = isset($_POST['serviceId']) ? sanitize_text_field($_POST['serviceId']) : '';
// Store user preference (you might use user meta or another storage method)
if ($service_id) {
$user_id = get_current_user_id();
update_user_meta($user_id, 'visible_service_' . $service_id, true);
}
wp_send_json_success();
}
add_action('wp_ajax_unhide_service', 'unhide_service_callback');
Adeyemi Oyinlola is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.