Hey im trying to dynamically (depending on post-id, regex pattern etc.) restrict access to URLs. Mainly those who points to attachments.
I tried to hook on the parse_request hook but it does not get fired when the URL is directly entered in the browser (e.g. example.com/wp-content/uploads/2022/07/test.txt)
Is there any hook that gets fired when accessing an URL directly or another way to programmatically restrict access to an URL?
Thanks
EmKo
My Answer:
You can achieve this by using the `template_redirect` hook in WordPress. This hook is fired before the template is loaded and can be used to restrict access to URLs based on certain conditions.
Here's an example code snippet that demonstrates how you can restrict access to URLs pointing to attachments:
php
add_action('template_redirect', 'restrict_attachment_access');
function restrict_attachment_access() {
global $post;
// Check if the current post is an attachment
if (is_attachment()) {
// Add your condition here to restrict access based on post ID, regex pattern, etc.
$post_id = $post->ID;
// Example condition: restrict access if post ID is even
if ($post_id % 2 == 0) {
// Redirect to homepage or any other page
wp_redirect(home_url());
exit;
}
}
}
You can modify the `restrict_attachment_access` function to add your specific conditions for restricting access to URLs pointing to attachments. This code will be triggered whenever an attachment URL is accessed directly in the browser.
Hope this helps! Let me know if you have any further questions.
Rate this post
5 of 5 based on 8008 votesComments