Update price of a product in a custom template woocommerce - php

I am trying to update the price from a custom page template. In my custom template I am writing these :
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
switch ($post_id) {
case '70':
echo the_title().'<br>';
$get_the_product_price = get_post_meta( get_the_ID(), '_regular_price', true);
$updated_product_price = $get_the_product_price+30;
update_my_price($post_id , $updated_product_price);
default:
break;
}
endwhile;
In functions.php I wrote this :
function update_my_price( $post_id , $updated_product_price) {
update_post_meta( $post_id, '_regular_price', $updated_product_price );
}
add_action( 'woocommerce_process_product_meta', 'update_my_price' );
The problem is Price is not being updated.
Any thought ?
Thanks in Advance.

Related

Woocommerce product sorting based on product views on popularity

I am trying to sort the products based on views, view counter is working fine, on findings I found that filter (woocommerce_get_catalog_ordering_args) and I checked this is implemented in woocommerce (/includes/class-wc-query.php Line no 583), it should be working fine but it's sorting product based on latest date instead of the views, I don't know what is causing the problem, can anyone check my code and suggest me the good solution or highlight my mistake.
//Product View Counter
add_action("wp", "product_view_counter");
function product_view_counter() {
global $post;
if ( is_product() ){
$meta = get_post_meta( $post->ID, "_total_views_count", true );
$meta = (int)($meta) ? $meta + 1 : 1;
update_post_meta( $post->ID, "_total_views_count", $meta );
}
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'woo_add_postmeta_ordering_args' );
function woo_add_postmeta_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ($orderby_value == "popularity"){
$sort_args['meta_key'] = '_total_views_count';
$sort_args['orderby'] = 'meta_value_num';
$sort_args['order'] = 'desc';
$sort_args['meta_type'] = 'NUMERIC';
}
return $sort_args;
}
Thank you

Improve the code for print json data

function add_price_calculate_tour() {
global $post;
$product = wc_get_product( $post->ID );
if( $product->is_type( 'tour_booking' ) ):
$priceAdult = (float) get_post_meta( $product->get_id(), '_regular_price', true );
$priceChild = (float) get_post_meta( $product->get_id(), 't_children_price', true );
$tour = json_encode(["priceAdult" => $priceAdult,"priceChild" => $priceChild]);
wp_add_inline_script( 'twentyseventeen-global', 'var tour = '.$tour.'', 'before' );
endif;
}
I would like to simplify or improve this code, what it does basically is to create an array with a value, and then create a json and print it in the footer.
Any suggestions?

Update all variations prices of a variable product in Woocommerce

I need to get all variation id and update price in loop.
Simple query and loop looks like:
$params = array(
‘posts_per_page’ => -1,
‘post_type’ => ‘product_variation’,
‘post_parent’ => $product->get_id() // tried $post-ID
);
$variations = get_posts( $params );
foreach ( $variations as $variation ) {
$variation_ID = $variation->ID; // tried $post-ID, $product->get_id()
$regular_price=34;
update_post_meta( $variation_ID, ‘_regular_price’, (float)$regular_price );
update_post_meta( $variation_ID, ‘_price’, (float)$regular_price );
}
This doesn't seem to work:
(‘post_parent’ => $product->get_id())
Neither does this:
($variation_ID = $variation->ID;).
First in your code ‘ or ’ should be replaced by '.
Also if used $post-ID should be replaced by $post->ID
Depending on where and how you are using this code, you should try to include global $post; first to be able to use the WP_Post object $post.
Then you could try to use this customized version of your code instead:
global $post;
$regular_price = 13;
// Only for product post type
if( $post->post_type == 'product' )
$product = wc_get_product( $post->ID ); // An instance of the WC_Product object
// Only for variable products
if( $product->is_type('variable') ){
foreach( $product->get_available_variations() as $variation_values ){
$variation_id = $variation_values['variation_id']; // variation id
// Updating active price and regular price
update_post_meta( $variation_id, '_regular_price', $regular_price );
update_post_meta( $variation_id, '_price', $regular_price );
wc_delete_product_transients( $variation_id ); // Clear/refresh the variation cache
}
// Clear/refresh the variable product cache
wc_delete_product_transients( $post->ID );
}
This code is tested on WooCommerce version 3+ and works

How to get all product in the WooCommerce programatically?

I want to get all the product data in the WooCommerce (product sku, name, price, stock count, availability and etc.) Can I do that using wp-query?
This way you can get all products via wp_query :
global $wpdb;
$all_product_data = $wpdb->get_results("SELECT ID,post_title,post_content,post_author,post_date_gmt FROM `" . $wpdb->prefix . "posts` where post_type='product' and post_status = 'publish'");
And if you want further product data then it will be like this :
$product = wc_get_product($product_id);
$product->product_type;
get_post_meta($prodyct_id, '_regular_price');
$product->get_available_variations();
Thanks for all reply.I have resolve that like billows
$full_product_list = array();
$loop = new WP_Query(array('post_type' => array('product', 'product_variation'), 'posts_per_page' => -1));
while ($loop->have_posts()) : $loop->the_post();
$theid = get_the_ID();
$product = new WC_Product($theid);
if (get_post_type() == 'product_variation') {
// ****************** end error checking *****************
} else {
$sku = get_post_meta($theid, '_sku', true);
$selling_price = get_post_meta($theid, '_sale_price', true);
$regular_price = get_post_meta($theid, '_regular_price', true);
$description=get_the_content();
$thetitle = get_the_title();
}
// add product to array but don't add the parent of product variations
if (!empty($sku))
$full_product_list[] = array("PartyID" => (int) $party_id,"Description"=> $description,
"ExternalNumber" => $theid, "ProductName" => $thetitle, "sku" => $sku,
"RegularPrice" => $regular_price, "SellingPrice" => $selling_price,
"ExternalProductCategoryId" => $cat_id, "ExternalProductCategoryName" => $cat_name);
endwhile;
When your building out your query set the post type to be product
$query->set('post_type', 'product');
And that will only search through woocommerce products.
Also if you are creating a theme, you can take any file from the /wp-content/plugins/woocommerce/templates/ directory and put it inside of /wp-content/themes/<yourTheme>/woocommerce to override any woocommerce page.
you can write this code in page that you want to display all product information
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 10
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<br />' . woocommerce_get_product_thumbnail().' '.get_the_title().'';
global $product;
//echo $product;
echo $product->get_id();
echo $product->get_name();
echo $product->get_sale_price();
echo $product->get_regular_price();
echo $product->get_sku();
echo $product->get_low_stock_amount();
echo $product->get_review_count();
echo $product->get_short_description();
$ratting = $product->get_rating_counts();
for($i = 0 ; $i < count($ratting); $i++) {
echo $ratting[i];
}
endwhile;
wp_reset_query();
?>
This is an old question; the answers using WP_Query() are obsolete since 2018.
See my answer here.

How to change post meta for all products on product add in WooCommerce?

So I am using woocommerce and am using a plugin called WP-All-Import to import a database of products into my Quickbooks connected e-commerce platform. Now I need to change the meta "_sync_status" to "on" for all products after this is complete. How would I do that for all products as they get added?
You first need to fetch all of the WooCommerce Products (post type of "product"), loop over each of them, and update the post meta for each. You can run this code by placing it in your functions.php in your theme, a file in the /wp-content/mu-plugins "must-use" plugins directory, or anonymously using a plugin like WordPress Developer + Console.
// args to fetch all products
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
// create a custom query
$products = new WP_Query( $args );
// if products were returned...
if ( $products->have_posts() ):
// loop over them....
while ( $products->have_posts() ):
// using the_post() to set up the $post
$products->the_post();
// use $post->ID to update the '_sync_status' post meta value
update_post_meta( $post->ID, '_sync_status', 'on' );
endwhile;
endif;
Thank you its work for me
i can update and add new post meta to my products.
// args to fetch all products
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
// create a custom query
$products = new WP_Query( $args );
// if products were returned...
if ( $products->have_posts() ):
// loop over them....
while ( $products->have_posts() ):
$products->the_post();
if (get_post_meta(get_the_ID(),'slide_template')=="" || !get_post_meta(get_the_ID(),'slide_template')){
update_post_meta( get_the_ID(), 'slide_template', 'default' );
echo get_the_ID().' do it'.'<br>';
}
endwhile;
endif;
The pre_post_update hook is called before the post is saved.
If you wish to do this when they get created or updated you can hijack the REQUEST array
add_action('pre_post_update', 'before_data_is_saved_function');
function before_data_is_saved_function($post_id) {
if ($_REQUEST['post_type'] == 'product') {
$_REQUEST['_sync_status'] = 'on';
}
}
If you only want to do this when they 'get added' use:
add_action('pre_post_update', 'before_data_is_saved_function');
function before_data_is_saved_function($post_id) {
if ($_REQUEST['post_type'] == 'product' && $_REQUEST['publish'] = 'Publish') {
$_REQUEST['_sync_status'] = 'on';
}
}

Categories