Set Default Post Format for Custom Post Types in WordPress

blog icon information internet

The post format can be set by using the save_post hook when saving the post. As setting the post format during the post saving process may trigger an infinite loop, we need to use remove_action and add_action within the function to avoid this.

The following examples are based on two post types, indieblocks_like and indieblocks_note, and show the code to be added to the functions.php file (or the Snippets plugin):

function set_default_post_format( $post_id, $post ) {
    // If this is an auto-save, we skip it
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

    // Set different default post formats for different post types
    switch( $post->post_type ) {
        case 'indieblocks_like':
            $format = 'link';
            break;
        case 'indieblocks_note':
            $format = 'status';
            break;
        default:
            return;
    }

    // Check the current post format, if not set, use the default
    if ( ! get_post_format( $post_id ) ) {
        // Before setting the post format, remove this function to prevent infinite loops
        remove_action( 'save_post', 'set_default_post_format', 10, 2 );
        set_post_format( $post_id, $format );
        // After setting the post format, add this function again
        add_action( 'save_post', 'set_default_post_format', 10, 2 );
    }
}
add_action( 'save_post', 'set_default_post_format', 10, 2 );

This function runs each time a post is saved, checks if the post format has been set, and if not, it sets the indieblocks_like post type to the link format and the indieblocks_note post type to the status format.

The above code can meet the following requirements: unless the post format is specifically specified during the editing process, it will be carried out according to the set default post format.

This is because, in the set_default_post_format function, the get_post_format function is first used to check if the post already has a post format. If the post already has a post format (meaning that the post format has been specified during the editing process), the function will return immediately and will not overwrite the set post format. Only when the post does not have a post format, will it set the default post format according to indieblocks_like and indieblocks_note.

Also, it is necessary to ensure that the theme already supports the post formats to be used. You can enable support with the following code:

add_theme_support( 'post-formats', array( 'link', 'status' ) );

Discover more from Sang-nguok

Subscribe now to keep reading and get access to the full archive.

Continue reading