Last active
June 22, 2024 21:14
-
-
Save Qubadi/f5b051f218d041fba58b6cae805916a7 to your computer and use it in GitHub Desktop.
Hide / Removing specific elements for users who are not logged in by ID.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dont forget to change ID #my-hide-1 to your CSS IDs | |
The custom code is a WordPress PHP script that securely modifies a webpage's HTML by removing specific elements for users who are not | |
logged in. It initiates an output buffer to capture the page content, then processes and filters it based on element IDs before the | |
content is rendered in the browser. This ensures that certain parts of the page are hidden from public view, enhancing privacy and | |
security. | |
// Start output buffering and register the callback function | |
function start_output_buffering() { | |
ob_start('callback_modify_html_output'); | |
} | |
// Callback function to modify the HTML output if the user is not logged in | |
function callback_modify_html_output($buffer) { | |
// Check if the user is not logged in | |
if (!is_user_logged_in()) { | |
// Create a new DOMDocument and load the HTML | |
$dom = new DOMDocument(); | |
libxml_use_internal_errors(true); // Use internal error handling | |
$dom->loadHTML(mb_convert_encoding($buffer, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); | |
libxml_clear_errors(); // Clear any errors that were ignored | |
// List all IDs you want to remove here | |
$elementIds = ['my-hide1', 'my-hide2', 'my-hide3']; | |
// Remove elements by IDs | |
foreach ($elementIds as $id) { | |
$element = $dom->getElementById($id); | |
if ($element) { | |
$element->parentNode->removeChild($element); | |
} | |
} | |
// Save the modified HTML back to the buffer | |
$buffer = $dom->saveHTML(); | |
} | |
// Return the buffer | |
return $buffer; | |
} | |
// End output buffering and send output to the browser | |
function end_output_buffering() { | |
ob_end_flush(); | |
} | |
// Hook functions to WordPress | |
add_action('get_header', 'start_output_buffering'); | |
add_action('wp_footer', 'end_output_buffering'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment