Code Snippets

Recent Code Snippets

Restrict REST API Access by IP Address

PHPfunction restrict_rest_api_by_ip($access) { // Define allowed IP addresses $allowed_ips = ['192.168.1.100', '203.0.113.0']; if (!in_array($_SERVER['REMOTE_ADDR'], $allowed_ips)) { return new WP_Error('rest_forbidden', 'Your…

November 14, 2024

Add Custom Authorization Header to REST API Requests

PHPfunction add_custom_authorization_header($request) { $headers = $request->get_headers(); // Add custom authorization header $headers['Authorization'] = 'Bearer ' . get_option('my_custom_api_token'); $request->set_headers($headers); return $request;…

November 14, 2024

Auto-Revoke Expired Application Passwords

PHPfunction revoke_expired_application_passwords() { $passwords = WP_Application_Passwords::get_application_passwords(get_current_user_id()); foreach ($passwords as $password) { // Check if password has expired (optional: adjust expiration…

November 14, 2024

Generate and Log Application Passwords for Specific Users

PHPfunction generate_app_password_on_login($user_login, $user) { // Create a new application password for this user $password = WP_Application_Passwords::create_application_password($user->ID); // Log the application…

November 14, 2024

Track Custom Referrals Using Cookies with WP_Http_Cookie

PHPfunction set_referral_cookie() { if (isset($_GET['referral']) && !isset($_COOKIE['user_referral'])) { $referral_code = sanitize_text_field($_GET['referral']); $cookie = new WP_Http_Cookie(array( 'name' => 'user_referral', 'value' =>…

November 14, 2024

Secure Session Token Management with WP_Http_Cookie

PHPfunction set_user_session_token() { if (is_user_logged_in()) { $user_id = get_current_user_id(); $session_token = hash('sha256', $user_id . AUTH_KEY . time()); $cookie = new…

November 14, 2024

Custom Cookie-Based User Redirect Using WP_Http_Cookie

PHPfunction set_last_category_visited_cookie() { if (is_category()) { $category = get_queried_object(); $cookie = new WP_Http_Cookie(array( 'name' => 'last_category_visited', 'value' => $category->slug, 'expires'…

November 14, 2024

Custom Scheduled Cleanup of Expired Transients

PHPfunction cleanup_expired_transients() { global $wpdb; $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP()"); } // Schedule the…

November 14, 2024

Scheduled Post Revisions Purge

PHPfunction delete_old_post_revisions() { global $wpdb; // Delete post revisions older than 3 months. $wpdb->query(" DELETE FROM {$wpdb->posts} WHERE post_type =…

November 14, 2024

Automated Inactive User Notification

PHPfunction send_inactive_user_reminders() { $inactive_users = get_users(array( 'meta_key' => 'last_login', 'meta_value' => strtotime('-6 months'), 'meta_compare' => '<', 'fields' => array('ID', 'user_email')…

November 14, 2024