Add default content to post (for specific category)

I’m trying to add some default content to my posts using this code in my functions.php:

add_filter( 'default_content', 'my_editor_content' );
function my_editor_content( $content ) {
$content = "My html content.";
return $content;
}

It works fine, but I would like to add the content to some categories only. This is tricky because the default content gets added while creating a new post, (so it is without a category). I followed this thread:
Force category choice before creating new post?
and the author came up with a way of forcing you to choose a category before wp creates the new post, but I don’t know how to edit the default content code so it is only applies to some categories?

Related posts

Leave a Reply

3 comments

  1. default_content runs when a post is loaded into the editor, actually. You can check for categories when the post is saved, but you’d want the save_post hook, probably. You want to check the $_REQUEST global.

    add_filter( 'default_content', 'my_editor_content' );
    function my_editor_content( $content ) {
      global $_REQUEST;
      if (isset($_REQUEST['post_category']) && in_array($some_category_id,$_REQUEST['post_category'])) {
        $content = "My html content.";
      }
      return $content;
    }
    

    … assuming no syntax errors. 🙂

    You probably also want to check if the post_content is empty and insert only it is.

  2. You can use the_content filter to add content to a category:

    function my_category_content ( $content ) {
        global $post;
        if ( is_single() ) {
            if ( in_category( "My Category", $post->ID ) ) {
                $content .= 'Add something';
            }
            return $content;
        } 
    } 
    add_filter( 'the_content', 'my_category_content' );
    

    This example will only display the added content on single posts though.

  3. 1) If you want default text in POST EDITOR, then use @Milo‘s answer.

    2) If you want add default content in front-end output of post,then use this code (in functions.php):

    function add_before_content($content) { global $post;
      if ( 'page' == $post->post_type ) {return 'YOUR MESSAGE'.$content;}
      if ( 'post' == $post->post_type ) {return 'YOUR MESSAGE'.$content;}
      //etc..........
    }
    add_filter('the_content', add_before_content);