I literally did this same thing this morning. Here’s a function that you can use. You can add the function to your functions.php (or wherever) and then call the function on your template:
/**
* @param array $product_ids product_id the product id for the product you want to retrieve.
*
* @return string the HTML output
*/
function wpse361339_relevant_products( $product_ids = [] ) {
global $post;
// Bail early if there is not product ids.
if ( is_empty( $product_ids ) ) :
return;
endif;
// Args here
$args = [
'post_type' => 'product',
'posts_per_page' => 1,
'post__in' => $product_ids,
// MORE ARGS HERE IF NECESSARY
];
$related_products = get_posts( $args );
$product_output="";
foreach ( $related_products as $related_product ) {
// Get the product object so we have access to the attributes.
$product = wc_get_product( $related_product->ID );
// $product_output .= BUILD YOUR MARKUP HERE
echo '<pre>' . print_r( $product, TRUE ) . '</pre>';
}
return $product_output;
}
I made it so you can pass whatever product ids you want as an array to the function. Then do what you want with the attributes.
To use on your template:
wpse361339_relevant_products( [ 'product_id_here' ] );
EDIT
To get the attributes in the WP_Query()
, you can simply do this inside of your while
loop:
$product_data = wc_get_product( get_the_ID() );
var_dump( $product_data );
In context:
<?php
$additional_forms_args = array(
'post_type' => 'product',
'posts_per_page' => 1,
'p' => $other_form_product_id
);
$additional_form_query = new WP_Query($additional_forms_args);
if ( $additional_form_query->have_posts() ) :
while ( $additional_form_query->have_posts() ) : $additional_form_query->the_post();
$product_data = wc_get_product( get_the_ID() );
var_dump( $product_data );
endwhile;
wp_reset_postdata();
endif;
To get specific product data you can use the methods from: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html
Like $product_data->get_title()
will get you the title.
EDIT 2
The checkbox data is saved in the product meta, so you get it:
$product_data->get_meta();