How I can show custom fields in my theme according to category?
For example in Laptop category show some custom fields and in Motherboard category show another fields.
How I can show custom fields in my theme according to category?
For example in Laptop category show some custom fields and in Motherboard category show another fields.
In your loop use has_term( $term, $taxonomy, $post )
.
if ( has_term( 'blue', 'product_color', $post ) )
{
$field = get_post_meta( $post->ID, 'field_name', TRUE );
if ( ! empty ( $field ) )
echo esc_html( $field );
}
If I understand the question OP want to check if a product has a category in woocommerce (the taxonomy is 'product_cat') and show product attributes according to that category. E.G. if a product is in 'Laptop' show 'CPU' and 'Ram' custom fields, if product is in 'Hard Disk' category show 'Capacity' and 'RPM' custom fields.
Am I right? If so you have to add something like this in your functions.php
function my_product_fields( $postid = 0 ) {
if ( ! intval($postid) ) {
global $post;
if ( empty($post) || ! is_object($post) || ! isset($post->ID) ) return;
$postid = $post->ID;
}
$cats = wp_get_object_terms( $postid, 'product_cat', array('fields' => 'slugs') );
$fields = array();
if ( in_array( 'laptop', $cats ) ) // 'laptop' is a category slug
$fields[] = array_merge($fields, array('cpu', 'ram', 'gpu');
if ( in_array( 'hdd', $cats ) )
$fields[] = array_merge($fields, array('capacity', 'rpm');
if ( in_array( 'pc_parts', $cats ) )
$fields[] = array_merge($fields, array('manufacturer');
if ( in_array( 'warranted', $cats ) )
$fields[] = array_merge($fields, array('warranty');
///.... and so on
if ( ! empty($fields) ) {
$out = '<ul>';
foreach ( $fields as $field ) {
$meta = get_post_meta( $postid, $field, TRUE );
if ( ! empty ( $meta ) ) $out .= '<li>' . esc_html( $meta ) . '</li>';
}
$out = '</ul>';
echo $out;
}
}
After that, when inside the loop, somewhere after the_post()
simply put:
my_product_fields();
When outside of the loop, to show the fields for a post, use
my_product_fields($postid);
If you want, to make function more flexible, you can put fields association with categories (all the lines like if ( in_array( 'cat_slug', $cats ) ) $fields[] = array_merge($fields, $array_of_cat_fields)
) in a separate file and require it from the function.