Using WordPress ‘private_title_format’ PHP filter

The ‘private_title_format’ filter allows you to modify the text that is prepended to the title of private posts in WordPress.

Table of contents

This filter is only applied on the front end.

Usage

add_filter( 'private_title_format', 'custom_private_title_format', 10, 2 );

function custom_private_title_format( $prepend, $post ) {
    // Your code here
    return $modified_prepend;
}

Parameters

  • $prepend (string)
    • Text displayed before the post title
    • Default value: 'Private: %s'
  • $post (WP_Post)
    • Current post object

Examples

Change the prefix text for private posts

add_filter( 'private_title_format', 'change_private_title_prefix', 10, 2 );

function change_private_title_prefix( $prepend, $post ) {
    return '[Restricted] %s';
}

In this example, the private post title prefix is changed from the default ‘Private: ‘ to ‘[Restricted] ‘.

Display private posts without a prefix

add_filter( 'private_title_format', 'remove_private_title_prefix', 10, 2 );

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

This code removes the prefix text for private posts, displaying only the post title.

Add custom prefix for specific post type

add_filter( 'private_title_format', 'custom_private_title_prefix_for_post_type', 10, 2 );

function custom_private_title_prefix_for_post_type( $prepend, $post ) {
    if ( $post->post_type === 'custom_post_type' ) {
        return '[Custom] %s';
    }
    return $prepend;
}

In this example, the prefix for private posts of the custom post type ‘custom_post_type’ is changed to ‘[Custom] ‘.

Change the prefix based on post category

add_filter( 'private_title_format', 'change_private_title_prefix_by_category', 10, 2 );

function change_private_title_prefix_by_category( $prepend, $post ) {
    $categories = get_the_category( $post->ID );
    foreach ( $categories as $category ) {
        if ( $category->slug === 'premium' ) {
            return '[Premium] %s';
        }
    }
    return $prepend;
}

This code changes the private post title prefix to ‘[Premium] ‘ if the post is in the ‘premium’ category.

Use post author’s display name as the prefix

add_filter( 'private_title_format', 'use_author_name_as_private_title_prefix', 10, 2 );

function use_author_name_as_private_title_prefix( $prepend, $post ) {
    $author_name = get_the_author_meta( 'display_name', $post->post_author );
    return $author_name . ': %s';
}

This example sets the private post title prefix to the author’s display name followed by a colon.

Leave a Comment

Your email address will not be published. Required fields are marked *