Get Woocommerce to Manage Stock as a default - wordpress

Is there a hook that would allow setting the Inventory > Manage Stock checkbox in woocommerce globally?
All my products are single item quantity, so it seems pretty counter-D.R.Y to always have to remember to check it, especially for other employees.

Although this is quite late, since you asked about a hook: although there doesn't appear to be a hook, action or function specifically for turning on the Manage Stock option, you can still hook into the post save function and auto-enable it that way, since it is just a post_meta value:
add_action('save_post', 'myWoo_savePost', 10, 2);
function myWoo_savePost($postID, $post) {
if (isset($post->post_type) && $post->post_type == 'product') {
update_post_meta($post->ID, '_manage_stock', 'yes');
}
}
Note that stock levels will always default to 0, so you may also want to add the line:
update_post_meta($post->ID, '_stock', '1');
...which will update your stock quantity to 1. Do be aware that this will happen every time a product is saved, though.
I'm unsure as to whether this has knock-on effects elsewhere in WooCommerce for larger stock quantities, but as you're dealing with single-quantity items, I'd guess you're probably okay.
Update (with $update):
As of Wordpress 3.7, a third parameter was added to save_post so you can easily tell if it's a new post being created or an existing post being updated. As such, you can fire the function above only when creating a new post (which is arguably the desired effect):
add_action('save_post_product', 'myWoo_savePost', 10, 3);
function myWoo_savePost($postID, $post, $update) {
if (!$update) {
// $update is false if we're creating a new post
update_post_meta($post->ID, '_manage_stock', 'yes');
update_post_meta($post->ID, '_stock', '1');
}
}
(Thanks to Dylan for the reminder about post-type specific saves)

A little late, but here's how for anyone else needing to do this... I found most of this code somewhere else, but I don't have the link anymore to where I found it. Tweaked it a little and this is what I ended up with (add to functions.php):
add_action( 'admin_enqueue_scripts', 'wc_default_variation_stock_quantity' );
function wc_default_variation_stock_quantity() {
global $pagenow, $woocommerce;
$default_stock_quantity = 1;
$screen = get_current_screen();
if ( ( $pagenow == 'post-new.php' || $pagenow == 'post.php' || $pagenow == 'edit.php' ) && $screen->post_type == 'product' ) {
?>
<!-- uncomment this if jquery if it hasn't been included
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
-->
<script type="text/javascript">
jQuery(document).ready(function(){
if ( !jQuery( '#_manage_stock' ).attr('checked') ) {
jQuery( '#_manage_stock' ).attr('checked', 'checked');
}
if ( '' === jQuery( '#_stock' ).val() ) {
jQuery( '#_stock' ).val(<?php echo $default_stock_quantity; ?>);
}
});
</script>
<?php
}
}

Woocommerce now has it's own hook for saving a product. For a simple product it's woocommerce_process_product_meta_simple.
Before updating the meta, we should first check that the _manage_stock is empty i.e. the checkbox has not been checked, so that it only triggers on products which have not already been set.
Then toggle the manage stock and set the default stock number.
function manage_stock_default( $post_id ) {
if (empty($_POST['_manage_stock'])) {
update_post_meta($post_id, '_manage_stock', 'yes');
update_post_meta($post_id, '_stock', '1');
}
}
add_action( 'woocommerce_process_product_meta_simple', 'manage_stock_default');

Related

Adding custom information after displaying comments in Wordpress, only in certain post type

I'm trying to show some calculated information after each comment, which are planned to be displayed only in 'product' post type. I have no problem with making the function work, it is showing what I want, but it also causes fatal errors on my website, for example the Comments section in admin panel. How can I make sure that these information are only shown in post type of 'product' and doesn't cause any errors anywhere else? My attempt is as follows:
function comment_significance_indicator ($content, $comment) {
global $wpdb;
global $current_user;
global $post;
$post_type = get_post_type( $post->ID );
if ($post_type === 'product') {
//some stuff happens here
return $content . $blabla;
else {
return $content;
}
}
add_filter("comment_text","comment_significance_indicator",50,2);
Thanks for any help.
write the code when the post_type == product like below:
if ($post_type === 'product') {
function your_func(){
return ;
}
add_filter("comment_text","comment_significance_indicator",50,2);
}

Remove JS file from Woocommerce Product edit pages

I am getting this error "Uncaught Error: Option 'ajax' is not allowed for Select2 when attached to a element." while updating Product Variation.
Actually there are 2 select2.js files, one from Woocommerce and other from 'WR PageBuilder' plugin. While I am renaming 'WR PageBuilder' select2.js file then its working fine. But that file is required for Editor.
I want to remove that js file only from Product pages.
I did 'wp_deregister_script()' and 'wp_dequeue_script()' but nothing happened.
Here is my code:
add_action('admin_init', 'functon_to_filter_script');
function functon_to_filter_script() {
global $typenow;
// when editing pages, $typenow isn't set until later!
if (empty($typenow)) {
// try to pick it up from the query string
if (!empty($_GET['post'])) {
$post = get_post($_GET['post']);
$typenow = $post->post_type;
}
}
if( 'product' == $typenow ){
add_action( 'admin_enqueue_scripts', 'deregister_my_script', 100 );
}
}
function deregister_my_script() {
wp_dequeue_script('wr-pagebuilder');
wp_deregister_script('wr-pagebuilder');
}
can anyone give me a solution?
This won't work because you are using the actions wrong.
Look here for the correct usage of action hooks:
Hooks in Wordpress
You are putting the admin_enqueue_scripts action hook inside of the admin_init action hook.
Try taking admin_enqueue_scripts outside of the admin_init hook like this:
global $typenow;
add_action( 'admin_enqueue_scripts', 'deregister_my_script', 100 );
function deregister_my_script() {
if (!empty($_GET['post'])) {
$post = get_post($_GET['post']);
$typenow = $post->post_type;
}
if( 'product' == $typenow ){
wp_dequeue_script('wr-pagebuilder');
wp_deregister_script('wr-pagebuilder');
}
}

Remove Calculate Fee Action Before Order Process

I have a custom function which i use to add/remove a custom fee to the Cart Totals. The fee works fine during the Cart Ajax Calculations, but for some reason the fee still gets charged to the order after checkout. How can I remove this before the order is processed? Here is what i currently have to calculate the fee:
function woo_add_cart_fee() {
global $woocommerce;
if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
return;
}
$checkout = WC()->checkout()->checkout_fields;
parse_str( $_POST['post_data'], $post_data );
// Add Fee if no VAT Number is Provided
if($post_data['vat_number'] == '' OR strlen($post_data['vat_number']) < 1 OR empty($post_data['vat_number'])){
$vat_total = 25; // $25.00 fee
$woocommerce->cart->add_fee( __('VAT Fee', 'woocommerce'), $vat_total );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
The problem is that once the user checks out, the fee is always added, even if they provide a VAT number (my custom field).
So I tried adding this snippet to remove the action completely before the order is processed, but this does not seem to work either:
function action_woocommerce_before_checkout_process( $array ) {
if($_POST['vat_number'] == '' OR strlen($_POST['vat_number']) < 1 OR empty($_POST['vat_number'])){
remove_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee', 1 );
}
}
// add the action
add_action( 'woocommerce_before_checkout_process', 'action_woocommerce_before_checkout_process');
I believe I may be using the wrong hook woocommerce_before_checkout_process because it doesn't seem to be firing.
Any Idea what could be happening? Thanks!
I was able to fix this by adding some control flow for $woocommerce->cart->add_fee It turns out that the calculate_totals function is run again before the thank you page
if(isset($_POST['vat_number'])){
if($_POST['vat_number'] == '' OR empty($_POST['vat_number'])){
$woocommerce->cart->add_fee( __($vat_label, 'woocommerce'), $vat_total );
}
} else {
$woocommerce->cart->add_fee( __($vat_label, 'woocommerce'), $vat_total );
}

WooCommerce inquiry if no price available

I'm helping a good friend setting up a WooCommerce shop. Since the shop is going to be bigger and the products are pretty variable and customizable we are not able to provide/configure all prizes from the beginning.
However we would like all products to be in the shop and ad an inquiry lead form in case no price is available.
Since I never programmed with WooCommerce I was wondering that is the right hook to implement such an functionality?
Had the exact same issue and couldn't find a plugin or a solution anywhere so I figured a workaround myself:
You need to edit file
/wp-content/themes/your-theme-name/woocommerce/single-product/add-to-cart/simple.php
(if it's not there just copy it from woocommerce plugin
/wp-content/plugins/woocommerce/templates/single-product/add-to-cart/simple.php)
and on line 14 where it says
if ( ! $product->is_purchasable() ) return;
you need to comment it out and write something like
if ( ! $product->is_purchasable() ) {
// put your code here
return;
}
and in the //put your code here line you can enter for example a shortcode for a form or a more complicated solution would be to put code for a button that when clicked will open up a popup form.
Still working on that ;)
Maybe too late, but I have had same issue currently.
Here is there code, Woocommerce uses to check if a product can be purchased:
https://github.com/woocommerce/woocommerce/blob/master/includes/abstracts/abstract-wc-product.php#L1404
Notice about: && '' !== $this->get_price()
/**
* Returns false if the product cannot be bought.
*
* #return bool
*/
public function is_purchasable() {
return apply_filters( 'woocommerce_is_purchasable', $this->exists() && ( 'publish' === $this->get_status() || current_user_can( 'edit_post', $this->get_id() ) ) && '' !== $this->get_price(), $this );
}
So you need to write a filter like this to override default:
add_filter( 'woocommerce_is_purchasable', function ( $is_purchasable, $product ) {
return $product->exists() && ( 'publish' === $product->get_status() || current_user_can( 'edit_post', $product->get_id() ) );
}, 10, 2 );
Try the following code snippet. You just have to put it in your functions.php. You don't need a plugin or to overwrite WooCommerce files in your child theme.
// Inquiry link if no price available
function add_inquiry_link_instead_price( $price, $product ) {
if ( '' === $product->get_price() || 0 == $product->get_price() ) :
return ''.__( 'Jetzt anfragen' ).'';
endif;
}
add_filter( 'woocommerce_get_price_html', 'add_inquiry_link_instead_price', 100, 2 );

WordPress Metabox saves on Update or Publish, but not on Saving Draft

I have created custom post types that also have custom meta_boxes I've created. Currently, they save when I publish or update a post, but they don't save when I'm in draft mode making changes.
add_action('save_post', 'save_details');
function save_details($post_id){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return $post_id;
}
if ($post->post_type == 'events') { // Check to see if Event Type.
update_post_meta($post->ID, "event_featuring", $_POST["event_featuring"]);
update_post_meta($post->ID, "event_time", $_POST["event_time"]);
update_post_meta($post->ID, "event_date", $_POST["event_date"]);
update_post_meta($post->ID, "event_end_date", $_POST["event_end_date"]);
update_post_meta($post->ID, "event_location", $_POST["event_location"]);
update_post_meta($post->ID, "empid", $_POST["empid"]);
update_post_meta($post->ID, "bhs_event", $_POST["bhs_event"]);
}
}
I tried using wp_insert_post_data instead of save_post, but then I had the opposite problem. It would save on Drafts, but publishing the post no longer worked. I tried calling both at the same time, same issue. What do I need to do differently so I can update a draft (before publishing) and it will save? I'm pretty sure this was working fine before I switched to 3.1.
save_post is called no matter what, be it a draft post, or a published post, so I am surprised that is not working. I do see a few oddities with your code though.
Considering you have the $post_ID, I would favor using that over the global $post. Also, I prefer the following method of detecting auto-drafts (I ripped it straight from wp-includes/post.php, I favor examining the Wordpress codebase and emulating their methods whenever possible).
Please try the following refactored code and let me know if this resolves your issue.
add_action("save_post", "save_details");
function save_details($post_ID = 0) {
$post_ID = (int) $post_ID;
$post_type = get_post_type( $post_ID );
$post_status = get_post_status( $post_ID );
if ( "events" == $post_type && "auto-draft" != $post_status ) {
update_post_meta($post_ID, "event_featuring", $_POST["event_featuring"]);
update_post_meta($post_ID, "event_time", $_POST["event_time"]);
update_post_meta($post_ID, "event_date", $_POST["event_date"]);
update_post_meta($post_ID, "event_end_date", $_POST["event_end_date"]);
update_post_meta($post_ID, "event_location", $_POST["event_location"]);
update_post_meta($post_ID, "empid", $_POST["empid"]);
update_post_meta($post_ID, "bhs_event", $_POST["bhs_event"]);
}
return $post_ID;
}

Resources