Is there any way to use default_content only for a certain post type, specifically product (WooCommerce)?

My code:

add_filter( 'default_content', 'set_default_content', 10, 2 );
function set_default_content( $content, $product ) {
    $content ='content to add to a post']';
    return $content;

I've tried with if ( 'product' == get_post_type() ) or even if ( 'page' == get_post_type() ) to test it but it's not working.


default_content is a filter used in the backend. You don't necessarily have anything in the loop so standard functions will probably fail. However, you're given a second argument of type WP_Post. You can check its post_type easily and work from there.

add_filter('default_content', 'WPSE_product_default_content', 10, 2);
function WPSE_product_default_content($post_content, $post) {
    if ($post->post_type !== 'product')
        return $post_content;

    $content ='content to add to a post'
    return $content;
| improve this answer | |
  • I actually manged to do it by calling the global variable inside the function. Is it considered a bad way to do it this way? add_filter( 'default_content', 'set_default_content', 10, 2 ); function set_default_content( $content, $post ) { global $post_type; if ('product' == $post_type) { $content ='[block id="2346"]'; return $content; } } – Sergiu Elmi Nov 27 '18 at 18:16
  • Not sure about good / bad practice. But can you trust the global variable? $post->post_type will always yield what you expect it. I have no idea what might manipulate global $post_type or what not – kero Nov 27 '18 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.