0

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.

3
  • To which object are these fields assigned? To terms, posts, users …?
    – fuxia
    Aug 3, 2013 at 15:01
  • to post, I want to use it in woocommerce plugin, and each product is a post-type Aug 3, 2013 at 15:05
  • What are the name of the custom fields? Aug 3, 2013 at 15:11

2 Answers 2

0

In your loop use has_term( $term, $taxonomy, $post ).

  1. Check if the post has the term you are searching for.
  2. Check if there is a value for the custom field.
  3. Print the value, but don’t forget to escape it.
if ( has_term( 'blue', 'product_color', $post ) )
{
    $field = get_post_meta( $post->ID, 'field_name', TRUE );

    if ( ! empty ( $field ) )
        echo esc_html( $field );
}
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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