Predefined Text for a New Post in WordPress (the_editor_content)

The note is not new, and I distinctly remember reading about this solution somewhere, but today I needed to set a predefined text for a new post, and for some reason, I couldn't find the solution quickly on the internet, so it turned out to be easier to do it myself.

This hack does NOT work with the new block editor (Gutenberg). Only with the classic editor.

In general, step by step

There is a custom post type different from post, called func, and I needed to make it so that when creating a new post of type func, the WordPress editor already had a predefined text. It is assumed that all posts of this type are template-based, so it is much easier when there is a text template in the editor.

This task is solved using a filter, and I knew that, but I couldn't quickly find this filter, in fact, I couldn't find a solution on the Internet at all - I'm a bad detective.

The necessary filter is called the_editor_content - it filters the content of the WordPress editor, regardless of which editor field is displayed, whether it's creating/editing a post or comment. Therefore, we will check whether to "modify" the text or not in the function that we will attach to the filter. It all looks very simple, like this:

add_filter( 'the_editor_content', 'new_post_content' );

function new_post_content( $content ){
	global $post;

	if ( ! $post->post_content && $post->post_type == 'post' ) {
		$content = "Here is some text that should be in the content field in a new post";
	}

	return $content;
}

With the condition if ( ! $post->post_content && $post->post_type == 'post' ), we check if this is a new post (the post has no content) and if the post type is post; if the condition is true, we write the text in the content field, if not, we simply return the text.

This code should be inserted into the theme's functions.php file.

It might be useful to someone.