Changing “Enter title here” based on post format

You need to do the following;

jQuery(document).ready(function( $ ) {

    $('input.post-format').click(function(){

    $('#title-prompt-text').val( $(this).next('label').text());

    })

});

This will replace the title with whichever post format you select.

Save the above into a file called custom-post-title.js and you will need to place this file into your theme folder. Either in the root or within a folder named /js/ – but just note that if you put it within a sub-folder make sure that you reflect this within the next snippet I give you.

Then in your theme functions.php file you need to enqueue your script for use in the admin area and in this case we will enqueue it on the post/page edit screens only (so it doesn’t unnecessarily load elsewhere and create overhead.

function custom_post_title($hook) {
    if( 'edit.php' != $hook )
        return;
    wp_enqueue_script( 'custom_post_title', get_bloginfo('template_directory') . '/custom-post-title.js', __FILE__) );
}
add_action( 'admin_enqueue_scripts', 'custom_post_title' );

Usuing admin_enqueue_scripts filter means we are only injecting our Javascript file on the backend (admin area) not on the front end, after all its useless to your users.

If you want to add a little further customization and change the default post title then use (also within your functions.php file);

function custom_title( $title ){

    $screen = get_current_screen();

    if ( 'post' == $screen->post_type ) {

    $title="Choose your post format";

    }

    return $title;

}

add_filter( 'enter_title_here', 'custom_title' );

This is something similar to what Rutwick posted above previously; although this does not address your immediate question, it does extend the level of customization so you can have,

  • A default post title upon entering the edit screen
  • The post title dynamically updated upon the selection of a post format.

Good luck!

Notes:

I’ve made an important update to the jQuery, by modifying;

$(‘#title-prompt-text’).text( $(this).val());

In favor of,

$(‘#title-prompt-text’).val( $(this).next(‘label’).text());

The former was grabbing its property from the “value” attribute of the input field and while this is perfectly fine to do in most cases, WP assigns the “Standard” post_format a value=0 instead of value=Standard – for all other post_formats the value is equal to that of its name.

The reason for this is because WP returns false when for example using the API function get_post_format(); thus this is how it decides to determine its default standard post. Which is a bit silly really, so the latter adjustment takes care of that by grabbing the value of the input fields adjacent <label> element instead which contains the name of our post format needed.

Leave a Comment