I've recently been working with Rohil_PHPBeginner who has been excellent and solved a big problem i had.
I need to now remove a particular category from the category list on the woo commerce product page.
Example: https://www.artgiftedbygod.co.uk/online-art-shop/jane-brighton/dawn-2/
You will see the Title, Artist name (which Rohil_PHPBeginner) solved, Price, Description, Availability, Buy Button, and then categories.
I would like to show all categories except the Artist name as this is now displayed under its own section.
This is the code that is found on the PHP page:
<?php
/**
* Single Product Meta
*
* #author WooThemes
* #package WooCommerce/Templates
* #version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $post, $product;
$cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );
$tag_count = sizeof( get_the_terms( $post->ID, 'product_tag' ) );
?>
<div class="product_meta">
<?php do_action( 'woocommerce_product_meta_start' ); ?>
<?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
<span class="sku_wrapper"><?php _e( 'SKU:', 'woocommerce' ); ?> <span class="sku" itemprop="sku"><?php echo ( $sku = $product->get_sku() ) ? $sku : __( 'N/A', 'woocommerce' ); ?></span>. </span>
<?php endif; ?>
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', $cat_count, 'woocommerce' ) . ' ', '.</span>' ); ?>
<?php echo $product->get_tags( ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.</span>' ); ?>
<?php do_action( 'woocommerce_product_meta_end' ); ?>
`
Try this :
<?php
/**
* Single Product Meta
*
* #author WooThemes
* #package WooCommerce/Templates
* #version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $post, $product;
$cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );
$tag_count = sizeof( get_the_terms( $post->ID, 'product_tag' ) );
?>
<div class="product_meta">
<?php do_action( 'woocommerce_product_meta_start' ); ?>
<?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
<span class="sku_wrapper"><?php _e( 'SKU:', 'woocommerce' ); ?> <span class="sku" itemprop="sku"><?php echo ( $sku = $product->get_sku() ) ? $sku : __( 'N/A', 'woocommerce' ); ?></span>.</span>
<?php endif; ?>
<?php
$cat_array = array();
$term_list = wp_get_post_terms($post->ID, 'product_cat', array("fields" => "all")); //get array containing category details
foreach($term_list as $cat_list)
{
array_push($cat_array, $cat_list->term_id);
}
$cat_id = ($term_list[0]->parent); //get parent category ID from the above generated array
$termchildren = get_term_children( '90' , 'product_cat' ); //New Line in Updattion -1
$final_result = array_diff($cat_array,$termchildren);
$new_ary = array_values($final_result);
$final_result_size = sizeof($new_ary);
$i=0;$j=0;
for($i=0;$i<$final_result_size;$i++){
$new_cat_id = $new_ary[$i];
$cat_url = get_term_link ($new_cat_id, 'product_cat'); //get link of parent ID
$term = get_term( $new_cat_id, 'product_cat' ); //Get Name of the parent from the parent ID
$name = $term->name; //Store it into an varialbe
if($j == 0):
echo "Categories: ";
endif;
echo "<a href='".esc_url($cat_url)."'>".$name."</a>";
if($i == ($final_result_size-1)):
echo "";
else:
echo ", ";
endif;
$j++;
}
?>
<?php echo $product->get_tags( ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.</span>' ); ?>
<?php do_action( 'woocommerce_product_meta_end' ); ?>
</div>
Related
I am having trouble adding the parent category to my URL in this code snippet. Any help would be appreciated.
Code is to show categories underneath products in woocommerce.
remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );
function VS_woo_loop_product_title() {
echo '<h3>' . get_the_title() . '</h3>';
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
// only displayed if the product has at least one category
$cat_links = array();
foreach ( $terms as $term ) {
$cat_links[] = ''.$term->name.'';
}
$on_cat = join( ", ", $cat_links );
?>
<div class="label-group">
<div class="categories-link"><?php echo $on_cat; ?></div>
</div>
<?php endif;
}
This code is outputting the Product (Brand) Category in (almost) the right spot - above the product title - on the Single Product Page.
How can I hyperlink it (Product Category) to the Product Category page? I essentially need to make this <?php echo $single_cat->name; ?> a dynamic hyperlink.
/** Output Product (Brand) Category on single product page **/
function add_brand_category(){
$product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );
if ( $product_cats && ! is_wp_error ( $product_cats ) ){
$single_cat = array_shift( $product_cats ); ?>
<h3 itemprop="name" class="product_category_title"><span><?php echo $single_cat->name; ?></span></h3>
<?php }
}
add_action( 'woocommerce_single_product_summary', 'add_brand_category', 2 );
You can use wc_get_product_category_list() – which returns the product categories in a list + adding a hyperlink to the product category page.
So you get:
function action_woocommerce_single_product_summary() {
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
echo '<h3 itemprop="name" class="product_category_title">';
echo wc_get_product_category_list( $product->get_id(), ', ', '<span>' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '</span>' );
echo '</h3>';
}
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 2 );
I'm using woocommerce for my website, but as I only have one main product and two accessories (related products), I don't need a classic shop page, neither single-product pages for each of my product. My main product has a color variation.
I want to have an add-to-cart button, with the color variation dropdown and the quantity field in one of my regular post page. Exactly like on a single-product page, but embedded in my own page, and without the parts of the single-product page I don't need (description, ...).
I finally decided to achieve this using two custom shortcodes I created: [my_vc_product_price id="xxx"] and [my_vc_add2cart_variable_product id="xxx"]. So I can put them where I want.
But my problem is that the behavior of the dropdown menu + variation availability + add-to-cart button is not the same that this elements have in the single-product page:
- the availability of he variation doesn't show up when I choose the color in the dropdown menu;
- the add-to-cart button is not disable when no color is chosen in the dropdown menu (it should be disable and active only when a color is chosen).
Displaying the price was easy, using some code found on internet:
/**
* Add shortcode to allow to display product price in a page
*/
function my_vc_display_product_price( $args ) {
$product_id = $args['id'];
$product = wc_get_product( $product_id );
echo '<p class="price">' . $product->get_price_html() . '</p>';
}
add_shortcode( 'my_vc_product_price', 'my_vc_display_product_price');
To get the same graphical result, I just had to add some CSS classes on the row: "woocommerce" and "product".
The code to display the dropdown menu + the quantity and the add-to-cart button is almost the same than in the variable.php file found in plugins/woocommerce/templates/single-product/add-to-cart/. The only things really change is that you need to get the "variation attributes" of the product, and not the attributes.
$attributes = $product->get_variation_attributes();
$attribute_keys = array_keys( $attributes );
So the full function code is:
/**
* Add shortcode to allow to display an add to cart button with dropdown menu for variation attributes
*/
function my_vc_add_to_cart_button_variable_product( $args ) {
global $product;
$product_id = $args['id'];
$product = wc_get_product( $product_id );
if( $product->is_type( 'variable' )) {
$attributes = $product->get_variation_attributes();
$attribute_keys = array_keys( $attributes );
$available_variations = array( $product->get_available_variations() );
do_action( 'woocommerce_before_add_to_cart_form' ); ?>
<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>" data-product_variations="<?php echo htmlspecialchars( wp_json_encode( $available_variations ) ) ?>">
<?php do_action( 'woocommerce_before_variations_form' ); ?>
<?php if ( empty( $available_variations ) && false !== $available_variations ) : ?>
<p class="stock out-of-stock"><?php _e( 'This product is currently out of stock and unavailable.', 'woocommerce' ); ?></p>
<?php else : ?>
<table class="variations" cellspacing="0">
<tbody>
<?php foreach ( $attributes as $attribute_name => $options ) : ?>
<tr>
<td class="value">
<?php
$selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( stripslashes( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) ) : $product->get_variation_default_attribute( $attribute_name );
wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>
<div class="single_variation_wrap">
<?php
/**
* woocommerce_before_single_variation Hook.
*/
do_action( 'woocommerce_before_single_variation' );
/**
* woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
* #since 2.4.0
* #hooked woocommerce_single_variation - 10 Empty div for variation data.
* #hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
*/
do_action( 'woocommerce_single_variation' );
?>
<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">{{{ data.variation.variation_description }}}</div>
<div class="woocommerce-variation-price">{{{ data.variation.price_html }}}</div>
<div class="woocommerce-variation-availability">{{{ data.variation.availability_html }}}</div>
</script>
<script type="text/template" id="tmpl-unavailable-variation-template">
<p><?php _e( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ); ?></p>
</script>
<?php
/**
* woocommerce_after_single_variation Hook.
*/
do_action( 'woocommerce_after_single_variation' );
?>
</div>
<?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
<?php endif; ?>
<?php do_action( 'woocommerce_after_variations_form' ); ?>
</form>
<?php
do_action( 'woocommerce_after_add_to_cart_form' );
}
}
add_shortcode( 'my_vc_add2cart_variable_product', 'my_vc_add_to_cart_button_variable_product');
Any idea what is going wrong? I don't understand, if the code is the same, why it didn't execute the same. Is there something missing because this code is outside woocommerce pages?
try using following code
function add_to_cart_form_shortcode( $atts ) {
if ( empty( $atts ) ) {
return '';
}
if ( ! isset( $atts['id'] ) && ! isset( $atts['sku'] ) ) {
return '';
}
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
);
if ( isset( $atts['sku'] ) ) {
$args['meta_query'][] = array(
'key' => '_sku',
'value' => sanitize_text_field( $atts['sku'] ),
'compare' => '=',
);
$args['post_type'] = array( 'product', 'product_variation' );
}
if ( isset( $atts['id'] ) ) {
$args['p'] = absint( $atts['id'] );
}
$single_product = new WP_Query( $args );
$preselected_id = '0';
if ( isset( $atts['sku'] ) && $single_product->have_posts() && 'product_variation' === $single_product->post->post_type ) {
$variation = new WC_Product_Variation( $single_product->post->ID );
$attributes = $variation->get_attributes();
$preselected_id = $single_product->post->ID;
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'p' => $single_product->post->post_parent,
);
$single_product = new WP_Query( $args );
?>
<script type="text/javascript">
jQuery( document ).ready( function( $ ) {
var $variations_form = $( '[data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>"]' ).find( 'form.variations_form' );
<?php foreach ( $attributes as $attr => $value ) { ?>
$variations_form.find( 'select[name="<?php echo esc_attr( $attr ); ?>"]' ).val( '<?php echo esc_js( $value ); ?>' );
<?php } ?>
});
</script>
<?php
}
$single_product->is_single = true;
ob_start();
global $wp_query;
$previous_wp_query = $wp_query;
$wp_query = $single_product;
wp_enqueue_script( 'wc-single-product' );
while ( $single_product->have_posts() ) {
$single_product->the_post()
?>
<div class="single-product" data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>">
<?php woocommerce_template_single_add_to_cart(); ?>
</div>
<?php
}
$wp_query = $previous_wp_query;
wp_reset_postdata();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
add_shortcode( 'add_to_cart_form', 'add_to_cart_form_shortcode' );
/*Example Usage [add_to_cart_form id=147]*/
That's just perfect! Many thanks.
Now the hardest to come: I need to understand your code and compare it with mine ;-)
I need order the results of "$product->get_categories()" with the slug.
The template use this code:
$cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );
//And after...
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', $cat_count, 'woocommerce' ) . ' ', '</span>' ); ?>
I've seen in a tutorial, that I can use this code,but doesn't work (in functions.php):
function wptt_cat_order( $args ){
$args['orderby'] = 'slug';
$args['order'] = 'ASC';
return $args;
} // wptt_cat_order
add_filter( 'woocommerce_product_subcategories_args', 'wptt_cat_order' );
Other question I have is(but not is so important than the other question), why he uses the $cat_count in "_n()" function and not "get_the_terms( $post->ID, 'product_cat' )"? first is only a number O_O.
Simple answer: you can't use that method to order the categories.
You're going to need to write your own loop using wp_get_post_terms(), which allows you to pass arguments (such as orderby). Something like the following should work (but I haven't tested it):
$args = array(
'orderby' => 'name',
);
$product_cats = wp_get_post_terms( $product->id, 'product_cat', $args );
$cat_count = sizeof( $product_cats );
echo '<span class="posted_in">' . _n( 'Category:', 'Categories:', $cat_count, 'woocommerce' );
for ( $i = 0; $i < $cat_count; $i++ ) {
echo $product_cats[$i]->name;
echo ( $i === $cat_count - 1 ) ? '' : ', ';
}
echo '</span>';
I am creating a woocommerce theme and I have product variations i.e. size which is displayed on product details page but problem is that I want to get all variations in my custom php page by using product id, can any one help me.
Thanks in advance.
You can use: $available_variations = $product->get_available_variations();
If this is a single style template, make sure you add global $product; near the top.
From there, you can foreach through the variations and do as you wish... since you didn't have any specific output I hope that this sets you on the right track.
You can use the code below:
global $woocommerce, $product, $post;
// test if product is variable
if ($product->is_type( 'variable' ))
{
$available_variations = $product->get_available_variations();
foreach ($available_variations as $key => $value)
{
//get values HERE
}
}
The following code:
$variations = $product->get_available_variations();
will return all variantion of product
This function is put where you show all variation:
\wp-content\plugins\woocommerce\templates\single-product\add-to-cart\variable.php
A common problem often starts from changing "In stock" or "Out of stock" labels for a single product. There are few solutions out there, where you need to change functions.php file and add a new filter.
The problems get more complicated when you need to modify this for product variations.
This may be your solution: http://bucketpress.com/changing-stock-availability-text-for-product-variations
In order to display available variations of the product you need to modify variable.php file, which can be found in
/wp-content/plugins/woocommerce/templates/single-product/add-to-cart/
Find this:
<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->id ); ?>" data-product_variations="<?php echo htmlspecialchars( json_encode( $available_variations ) ) ?>">
and before tag paste this code:
foreach( $available_variations as $i => $variation ) {
//check if variation has stock or not
if ( $variation['is_in_stock'] ) {
// Get max qty that user can purchase
$max_qty = $variation['max_qty'];
// Prepare availability html for stock available instance
$availability_html = '<p class="stock in-stock">' . $max_qty . ' units available for your purchase.' . '</p>';
} else {
// Prepare availability html for out of stock instance
$availability_html = '<p class="stock out-of-stock">Oops, we have no stock left.</p>';
}
$available_variations[$i]['availability_html'] = $availability_html; }
Don't forget to move php end tag "?>" from this line
do_action( 'woocommerce_before_add_to_cart_form' ); ?>
after your new code.
So the complete variable.php file should like something like this (WooCommerce 3.2.4):
<?php
/**
* Variable product add to cart
*
* This template can be overridden by copying it to yourtheme/woocommerce/single-product/add-to-cart/variable.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* #see https://docs.woocommerce.com/document/template-structure/
* #author WooThemes
* #package WooCommerce/Templates
* #version 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
global $product;
$attribute_keys = array_keys( $attributes );
do_action( 'woocommerce_before_add_to_cart_form' );
// Your New Code goes here:
foreach( $available_variations as $i => $variation ) {
// check if variation has stock or not
if ( $variation['is_in_stock'] ) {
// Get max qty that user can purchase
$max_qty = $variation['max_qty'];
// Prepare availability html for stock available instance
$availability_html = '<p class="stock in-stock">Available: ' . $max_qty . '</p>';
} else {
// Prepare availability html for out of stock instance
$availability_html = '<p class="stock out-of-stock">Out of stock!</p>';
}
$available_variations[$i]['availability_html'] = $availability_html;
} ?>
<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>" data-product_variations="<?php echo htmlspecialchars( wp_json_encode( $available_variations ) ) ?>">
<?php do_action( 'woocommerce_before_variations_form' ); ?>
<?php if ( empty( $available_variations ) && false !== $available_variations ) : ?>
<p class="stock out-of-stock"><?php _e( 'This product is currently out of stock and unavailable.', 'woocommerce' ); ?></p>
<?php else : ?>
<table class="variations" cellspacing="0">
<tbody>
<?php foreach ( $attributes as $attribute_name => $options ) : ?>
<tr>
<td class="label"><label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?></label></td>
<td class="value">
<?php
$selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( stripslashes( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) ) : $product->get_variation_default_attribute( $attribute_name );
wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
echo end( $attribute_keys ) === $attribute_name ? apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#">' . esc_html__( 'Clear', 'woocommerce' ) . '</a>' ) : '';
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>
<div class="single_variation_wrap">
<?php
/**
* woocommerce_before_single_variation Hook.
*/
do_action( 'woocommerce_before_single_variation' );
/**
* woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
* #since 2.4.0
* #hooked woocommerce_single_variation - 10 Empty div for variation data.
* #hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
*/
do_action( 'woocommerce_single_variation' );
/**
* woocommerce_after_single_variation Hook.
*/
do_action( 'woocommerce_after_single_variation' );
?>
</div>
<?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
<?php endif; ?>
<?php do_action( 'woocommerce_after_variations_form' ); ?>
</form>
<?php
do_action( 'woocommerce_after_add_to_cart_form' );
All credits to "Kevin" from: http://bucketpress.com/author/base-admin
Try this,
<?php
$name_size = get_post_meta($_GET['pr_id'],'product_size', true);
$t_shirt_sizes_array = wp_get_post_terms($_GET['pr_id'],'pa_size');
$t_shirt_size = array();
$t_shirt_price = array();
for($scnt = 0; $scnt < count($t_shirt_sizes_array); $scnt++){
$t_shirt_size[] = $t_shirt_sizes_array[$scnt]->name;
$t_shirt_price[] = $t_shirt_sizes_array[$scnt]->slug;
$t_shirt_size_id[] = $t_shirt_sizes_array[$scnt]->term_id;
}
$cnt = 1;
for($i = 0; $i < count($t_shirt_size); $i++){
$name_size = $t_shirt_size[$i];
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name =
'".$t_shirt_size[$i]."'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = ".$_GET['pr_id'];
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
echo $name_size;
$_product = new WC_Product_Variation( $variation_id[0] );
echo $_product->get_price();
}
$price = $t_shirt_price[$i];
$cnt++;
}
?>