Adding a prefix to a post title

There are probably a few ways to handle this. Here’s one way using a checkbox to enable the prefix for individual posts, and a filter on the_title to add the prefix whenever the_title() is called for those posts.

1. Add a meta box for an on/off checkbox

a. Add the meta box to the post edit screen

function wpd_title_prefix_register_meta_box() {
    add_meta_box(
        'wpd-title-prefix',
        'Title Has Prefix?',
        'wpd_title_prefix_meta_box',
        'post',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'wpd_title_prefix_register_meta_box' );

b. Render the meta box

function wpd_title_prefix_meta_box( $post ){
    $checked = get_post_meta( $post->ID, '_wpd_title_prefix', true );
    ?>
    <input type="checkbox" name="wpd-title-prefix" <?php checked( $checked ); ?> /> Yes
    <?php
}

c. Save the meta box value

function wpd_title_prefix_save_meta( $post_id ) {
    if( isset( $_POST['wpd-title-prefix'] ) ){
        update_post_meta( $post_id, '_wpd_title_prefix', 1 );
    } else {
        delete_post_meta( $post_id, '_wpd_title_prefix' );
    }
}
add_action( 'save_post', 'wpd_title_prefix_save_meta' );

2. Filter the_title and add the prefix to posts that were checked

function wpd_title_prefix_filter( $title, $post_id ) {
    if( $checked = get_post_meta( $post_id, '_wpd_title_prefix', true ) ){
        $title="[30 Second Read]: " . $title;
    }
    return $title;
}
add_filter( 'the_title', 'wpd_title_prefix_filter', 10, 2 );

Leave a Comment