0

A little extra info:

I have created a custom product type within WooCommerce. The add_meta_box function only accepts a 'post_type' argument. This means that I can get it on all products no problem, but I want to only render it on a subset of the 'product' post_type, based on 'product_type'.

This is the code I am using just inside my metabox class:

public function __construct() {
    add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
}

public function add_meta_box( $post_type ) {
    $post_types = array('product');     //limit meta box to certain post types
    if ( in_array( $post_type, $post_types )) {
        add_meta_box(
            'wf_child_letters'
            ,__( 'Picture Preview', 'woocommerce' )
            ,array( $this, 'render_meta_box_content' )
            ,$post_type
            ,'advanced'
            ,'high'
        );
    }
}

I have tried using get_post() within the function to check the product type of the current page, doesnt work, must not load the page before the meta box. I have tried using the $post variable that can be passed with this hook, when I tried to $post->product_type I got a non-object error, so I dont think I understand what that parameter is in that hook.

Any advice would be appreciated, I am trying to adopt as much Wordpress best practice as I can and really understand its architecture, so feel free to over explain.

  • 1
    Mind if I ask how this is off topic? I am asking about the use of Wordpress functions and why the ones I am using arent available to me where I want to use them. – Coltarain Oct 7 '14 at 0:18
2

You should be able to get the current product id using the using the $post global variable and use that with the WooCommerce function get_product() to the the product object and test its product type.

public function __construct() {
    add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
}

public function add_meta_box( $post_type ) {
    $post_types = array('product');     //limit meta box to certain post types
    global $post;
    $product = get_product( $post->ID );
    if ( in_array( $post_type, $post_types ) && ($product->product_type == 'simple' ) ) {
        add_meta_box(
            'wf_child_letters'
            ,__( 'Picture Preview', 'woocommerce' )
            ,array( $this, 'render_meta_box_content' )
            ,$post_type
            ,'advanced'
            ,'high'
        );
    }
}

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