Reputation: 18725
I use wc_get_product
function to update the product's price. I hardcoded the ID 80 to see if it works but it probably returns false
.
I don't understand why since I can clearly see that my first product has ID = 80.
I use this plugin https://wordpress.org/plugins/code-snippets/
and this is the code:
$product = wc_get_product( 80 );
$product->set_sale_price( 100 );
$product->set_price( 100 );
$product->save();
Can you tell me where is the problem? I get this error:
Na řádku č. 2 v souboru /data/a/7/a7833039-4699-4c19-96a3-4e99cb97fa3f/premi.cz/web/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code došlo k chybě typu E_ERROR. Chybová zpráva: Uncaught Error: Call to a member function set_sale_price() on bool in /data/a/7/a7833039-4699-4c19-96a3-4e99/premi.cz/web/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code:2
Stack trace:
#0 /data/a/7/a7833039-4699-4c19-96a3-4e99cb97fa3f/premi.cz/web/wp-content/plugins/code-snippets/php/snippet-ops.php(446): eval()
#1 /data/a/7/a7833039-4699-4c19-96a3-4e99cb97fa3f/premi.cz/web/wp-content/plugins/code-snippets/php/snippet-ops.php(534): execute_snippet('$product = wc_g...', 6)
#2 /data/a/7/a7833039-4699-4c19-96a3-4e99cb97fa3f/premi.cz/web/wp-includes/class-wp-hook.php(288): execute_active_snippets('')
#3 /data/a/7/a7833039-4699-4c19-96a3-4e99cb97fa3f/premi.cz/web/wp-includes/class-wp-hook.php(312): WP_Hook->apply_filters(NULL, Array)
#4 /data/a/7/a7833039-4699-4c19-96a3-4e99cb97fa3f/premi.cz/web/wp-includes/plugin.php(478): WP_Hook->do_action(Array)
#5 /data/a/7/a7833039-4699-4c19-96a3-4e99cb97fa3f/premi.cz/web/wp-sett
Upvotes: 0
Views: 4072
Reputation: 5824
I am facing same problem. I know it's too late for answer this questoin and Also you found a solution for it. But I am going to answer because it's helpful for other user also.
I found the good and working solution. Just create the WooCommerce product factory object and get the product through it. Then after, You able to change the product price like.
$productId = 80;
$_pf = new WC_Product_Factory();
$product = $_pf->get_product( $productId );
$product->set_price( 100);
$product->set_regular_price( 100 );
$product->set_sale_price( 100 );
$product->save();
It's works for me. I hope this helpful for other people also. If you need more detail about it Then Just follow this TryVary tutorial.
Upvotes: 2