0
votes

Appreciate all the guidance I can get on this one.

I am working on a shop using WordPress and Woocommerce. I have a custom order form that I want to display on each product in a specific product category. My idea is to use an ACF field with true/false checkbox to determine whether the products in this category should have an order form or not.

The checkbox is located here:

enter image description here

enter image description here

So I don't want to name a specific product category in my code, instead I want to check if a single product belongs to a category which has a checked checkbox for the order form.

My issue is that I don't understand how to display the order form in a products post when checking the box, without the need to add it in all posts that should display it. Is it possible to access my ACF from a single product when it is added in the taxonomy product_cat? Any ideas?

I found the get_the_terms function but I am not sure how to use it. This is how I've been trying to access my ACF:

function test() {
 global $post;
 $terms = get_the_terms( $post->ID, 'product_cat' );
 $queried_object = get_queried_object(); 
 $taxonomy = $queried_object->taxonomy;
 $term_id = $queried_object->term_id;  

 $checked_form = get_field('orderform', $taxonomy . '_' . $term_id);
 if($checked_form) {
      echo 'Checked!';
 }else{
      echo 'Not checked';
      var_dump($terms);
      var_dump($checked_form);
      var_dump($term_id);
 }
}
add_action('woocommerce_single_product_summary', 'test');
1

1 Answers

0
votes

So I figured it out. I post my solution here in case someone else is looking for guidance. After var_dumping get_the_terms( $post->ID, 'product_cat' ) I thought I might have to loop through each item in WP_term object and then used the term_id and taxonomy to retrieve the value from my ACF.

function woo_custom_order_form() {

 global $post;
 $terms = get_the_terms( $post->ID, 'product_cat' );

 if($terms) {
   foreach($terms as $term) {
        $term_id = $term->term_id;
        $taxonomy = $term->taxonomy;
   }
 }
 $checked_form = get_field('orderform', $taxonomy . '_' . $term_id);

 if($checked_form) {
      // Adds nav button that opens form
      add_action('woocommerce_single_product_summary','add_nav_to_single_product_form', 20);
      // Adds form on single product page
      add_action('woocommerce_single_product_summary', 'add_form_to_single_product', 10);
      // Filter hook for cf7 form on single product page
      add_filter('wpcf7_form_tag', 'add_variations_to_order_form', 10, 2);
      remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
 }
}
add_action( 'wp', 'woo_custom_order_form' );