Using WordPress ‘protected_title_format’ PHP filter

The ‘protected_title_format’ filter allows you to modify the text that is displayed before the title of a protected WordPress post. This filter is only applied on the front end.

Usage

To use this filter, you need to add a custom function to your theme’s functions.php file or create a custom plugin. Then, hook your function to the ‘protected_title_format’ filter using add_filter().

add_filter( 'protected_title_format', 'my_custom_protected_title', 10, 2 );

function my_custom_protected_title( $prepend, $post ) {
    // Your custom code goes here
}

Parameters

  • $prepend (string): The text displayed before the post title. Default value is ‘Protected: %s’.
  • $post (WP_Post): The current post object.

Examples

Change Protected Title Prefix

Scenario: Change the text displayed before the title of protected posts.

add_filter( 'protected_title_format', 'change_protected_title_prefix', 10, 2 );

function change_protected_title_prefix( $prepend, $post ) {
    return 'Private: %s';
}

Explanation: This code changes the protected title prefix from ‘Protected’ to ‘Private’.

Add a Lock Emoji to Protected Title

Scenario: Add a lock emoji before the protected post title.

add_filter( 'protected_title_format', 'add_lock_emoji_to_protected_title', 10, 2 );

function add_lock_emoji_to_protected_title( $prepend, $post ) {
    return '🔒 Protected: %s';
}

Explanation: This code adds a lock emoji before the protected post title.

Remove the Protected Title Prefix

Scenario: Remove the text displayed before the title of protected posts.

add_filter( 'protected_title_format', 'remove_protected_title_prefix', 10, 2 );

function remove_protected_title_prefix( $prepend, $post ) {
    return '%s';
}

Explanation: This code removes the protected title prefix, displaying only the post title.

Add Post ID to Protected Title

Scenario: Display the post ID before the protected post title.

add_filter( 'protected_title_format', 'add_post_id_to_protected_title', 10, 2 );

function add_post_id_to_protected_title( $prepend, $post ) {
    return 'Protected [ID: ' . $post->ID . ']: %s';
}

Explanation: This code adds the post ID before the protected post title.

Change Protected Title Based on Category

Scenario: Change the protected post title prefix based on the post category.

add_filter( 'protected_title_format', 'change_protected_title_based_on_category', 10, 2 );

function change_protected_title_based_on_category( $prepend, $post ) {
    if ( in_category( 'members-only', $post ) ) {
        return 'Members Only: %s';
    }
    return $prepend;
}

Explanation: This code checks if the post is in the ‘members-only’ category. If it is, the protected title prefix is changed to ‘Members Only’. If not, the default prefix is used.