I am really struggling with WooCommerce PHP. This time I am simply trying to see if a product post has a tag before continuing to add a custom metabox. The code is written into functions.php of the child theme.
global $wp_query;
$id = $wp_query->post->ID;
if ( ! has_tag( "hasparts", $id )) {
die; // used return also
} else {
// add metabox
}
I get the following error
Warning: Attempt to read property "ID" on null in C:\xampp\htdocs\wiz_invent\wp-content\themes\storefront-child\functions.php on line 14
I do not seem to be able to get my head around how to find basic post properties (ID, SKU) or how and where to use $post variable.
WooCommerce Tag is a custom taxonomy, so it will work with WordPress has_term()
and product_tag
taxonomy for WooCommerce tag.
Below is a complete example based on your requirement:
// Add a metabox to WooCommerce Product conditionally
add_action( 'add_meta_boxes', 'admin_product_custom_metabox' );
function admin_product_custom_metabox() {
if( has_term( array('hasparts'), 'product_tag') ) {
add_meta_box(
'custom',
__('Custom Meta Box'),
'custom_metabox_content_callback',
'product',
'normal',
'high'
);
}
}
// Metabox content callback function
function custom_metabox_content_callback() {
echo 'Here goes the metabox content…';
}
Code goes on functions.php file of your child theme (or in a plugin). Tested and works.