Skip to content

Instantly share code, notes, and snippets.

@benpearson
Created January 9, 2025 07:17
Show Gist options
  • Save benpearson/503d85e740be96e52d21570c2243e278 to your computer and use it in GitHub Desktop.
Save benpearson/503d85e740be96e52d21570c2243e278 to your computer and use it in GitHub Desktop.
WordPress: Password protected content helpers
<?php
/**
* Helpers: Password protected content
*/
/**
* Remove "Protected:" prefix from the title of password protected posts
*/
function dt_remove_protected_prefix_from_titles($var, $post)
{
return '%s';
};
add_filter('protected_title_format', 'dt_remove_protected_prefix_from_titles', 10, 2);
/**
* Get the id of closest password protected post.
* Start with current post and work up the ancestors
*/
function dt_related_password_protected_post_id($post = null)
{
if (!is_page()) {
return false;
}
$post = get_post($post);
$ancestors = get_ancestors($post->ID, 'page');
$all_relevant_post_ids = array_merge([$post->ID], $ancestors);
foreach ($all_relevant_post_ids as $post_id) {
$current_post = get_post($post_id);
if (!empty($current_post->post_password)) {
return $post_id;
}
}
return false;
}
/**
* Wrapper for core function post_password_required() that also considers
* if parents are password protected
*/
function dt_post_password_required()
{
$pasword_protected_ancestor_id = dt_related_password_protected_post_id();
return post_password_required($pasword_protected_ancestor_id);
}
/**
* Wrapper for core function get_the_password_form() that also considers
* if parents are password protected
*/
function dt_get_the_password_form()
{
$pasword_protected_ancestor_id = dt_related_password_protected_post_id();
return get_the_password_form($pasword_protected_ancestor_id);
}
/**
* Get all page ids that either have a password or have an ancestor that has a password.
*/
function dt_get_all_password_protected_page_ids()
{
$all_protected_page_ids = [];
$password_pages_query = [
'posts_per_page' => -1,
'post_type' => 'page',
'has_password' => true,
'fields' => 'ids',
];
$page_ids_with_passwords = get_posts($password_pages_query);
if ($page_ids_with_passwords) {
foreach ($page_ids_with_passwords as $ancestor_page_id) {
if (!in_array($ancestor_page_id, $all_protected_page_ids)) {
$all_protected_page_ids[] = $ancestor_page_id;
}
$get_pages_args = [
'child_of' => $ancestor_page_id,
];
$child_pages_array = get_pages($get_pages_args);
if ($child_pages_array) {
foreach ($child_pages_array as $child_page_obj) {
if (!in_array($child_page_obj->ID, $all_protected_page_ids)) {
$all_protected_page_ids[] = $child_page_obj->ID;
}
}
}
}
}
return $all_protected_page_ids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment