Woocommerce terms and conditions in iframe

function design_woocommerce_checkout_terms_and_conditions()
{
	remove_action('woocommerce_checkout_terms_and_conditions', 'wc_terms_and_conditions_page_content', 30);
}

if ((!defined('MAIN_SITE') || !MAIN_SITE) && !in_array(COUNTRY_NAME, ['Switzerland'])) {
	add_action('wp', 'design_woocommerce_checkout_terms_and_conditions');
}

 

Woocommerce получить список урлов товаров

Иногда необходимо быстро получить список адресов страниц всех опубликованных на сайте товаров. Для этого необходимо выполнить данный php скрипт, который можно разместить в корне сайта.

<?php
include( 'wp-load.php' );
// Setup your custom query
$args = [
    'post_type' => ['product'/*, 'post', 'page'*/],
    'posts_per_page' => -1,
    'post_status' => 'publish'
];
$loop = new WP_Query( $args );
 
while ( $loop->have_posts() ) : $loop->the_post();
	global $post;	
	$product = wc_get_product( $post->ID );	
	$permalink = $product->get_permalink();
	echo $permalink.'<br/>';	
endwhile; wp_reset_query(); // Remember to reset 

?>

Установить sku товару и вариациям

<?php
include( 'wp-load.php' );
$list = [];
$args = [
    'post_type' => ['product'/*, 'post', 'page'*/],
    'posts_per_page' => -1,
    'post_status' => 'publish'
];
$loop = new WP_Query( $args );
$list = array();
while ( $loop->have_posts() ) : $loop->the_post();
	global $post;	
	$product = wc_get_product( $post->ID );		
	$max_sku = '100000000'.time();
		if(empty($product->get_sku())){
			$product->set_sku($max_sku);
		}
		if( $product->is_type('variable')) {
			$children_ids = $product->get_children();
			foreach( $children_ids as $child_id ){
				$max_sku = '100000000'.generateRandomString().time();
				$variation = wc_get_product($child_id);
				if(get_post_meta($variation->get_id(), '_sku', true) === ''){
					$variation->set_sku( $max_sku );
					$variation->save();
				}
			}
		}
	 
endwhile; wp_reset_query(); // Remember to reset 
?>

Woocommerce округлить цены

<?php
include( 'wp-load.php' );
// id => sku from com domain
// Setup your custom query
$args = [
    'post_type' => ['product'/*, 'post', 'page'*/],
    'posts_per_page' => 200,
    'post_status' => 'publish'
];
function p($a, $d = 1) {
	echo '<pre>';
	var_dump($a);
	if($d) {
		die;
	}
}
$loop = new WP_Query( $args );
$list = array();
while ( $loop->have_posts() ) : $loop->the_post();
	global $post;	
	$product = wc_get_product( $post->ID );
	if ( $product->is_type( 'variable' ) ) {
		//$variations = $product->get_variations();
		$variations = $product->get_children();
		foreach($variations as $ir => $var) {
			$variation = new WC_Product_Variation( $var );
			$a = 0;
			if ($variation->get_sale_price() && (int) $variation->get_sale_price() != $variation->get_sale_price()) {
				$variation->set_sale_price(round($variation->get_sale_price()));
				$a = 1;
			}
			if ($variation->get_regular_price() && (int) $variation->get_regular_price() != $variation->get_regular_price()) {
				$variation->set_regular_price(round($variation->get_regular_price()));
				$a = 1;
			}
			if ($variation->get_price() && (int) $variation->get_price() != $variation->get_price()) {
				$variation->set_price(round($variation->get_price()));
				$a = 1;
			}
			if($a) {
				$variation->save();
			}
		}
	}
	elseif( $product->is_type( 'simple' )) {
		$a = 0;
		if ($product->get_sale_price() && (int) $product->get_sale_price() != $product->get_sale_price()) {
			$product->set_sale_price(round($product->get_sale_price()));
			$a = 1;
		}
		if ($product->get_regular_price() && (int) $product->get_regular_price() != $product->get_regular_price()) {
			$product->set_regular_price(round($product->get_regular_price()));
			$a = 1;
		}
		if ($product->get_price() && (int) $product->get_price() != $product->get_price()) {
			$product->set_price(round($product->get_price()));
			$a = 1;
		}
		if($a) {
			$product->save();
		}
	}
	 
endwhile; //wp_reset_query(); // Remember to reset
echo 'All product loop  done<br>';
/*foreach ($list as $key => $value){
    echo '"'.$key.'"'.' => '.'"'.$value.'"'.', ';
}*/
?>

Buy now for woocommerce

/* Dynamic Button for Simple & Variable Product */

/**
 * Main Functions
*/

function sbw_wc_add_buy_now_button_single()
{
    global $product;
    printf( '<button id="sbw_wc-adding-button" type="submit" name="sbw-wc-buy-now" value="%d" class="single_add_to_cart_button buy_now_button button alt">%s</button>', $product->get_ID(), esc_html__( 'Buy Now', 'sbw-wc' ) );
}

add_action( 'woocommerce_after_add_to_cart_button', 'sbw_wc_add_buy_now_button_single' );



/*** Handle for click on buy now ***/

function sbw_wc_handle_buy_now()
{
    if ( !isset( $_REQUEST['sbw-wc-buy-now'] ) )
    {
        return false;
    }

    WC()->cart->empty_cart();

    $product_id = absint( $_REQUEST['sbw-wc-buy-now'] );
    $quantity = absint( $_REQUEST['quantity'] );

    if ( isset( $_REQUEST['variation_id'] ) ) {

        $variation_id = absint( $_REQUEST['variation_id'] );
        WC()->cart->add_to_cart( $product_id, $quantity, $variation_id );

    }else{
        WC()->cart->add_to_cart( $product_id, $quantity );
    }

    wp_safe_redirect( wc_get_checkout_url() );
    exit;
}

add_action( 'wp_loaded', 'sbw_wc_handle_buy_now' );

/* Dynamic Button for Simple & Variable Product Closed */

Show list out of stock products

<?php
include( 'wp-load.php' );
// Setup your custom query
$args = [
    'post_type' => ['product'/*, 'post', 'page'*/],
    'posts_per_page' => -1,
    'post_status' => 'publish'
];
$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
	global $post;	
	$product = wc_get_product( $post->ID );		
	if($product->get_stock_status() == 'outofstock'){
		echo 'Out of stock simple product ID: '.$post->ID.' link: '.get_permalink( $product->ID ).' Title: '.$product->get_title().'<br>';
	}
	 if ($product->get_type() == "variable" && $post->post_name != 'bra') {		
        $variations = $product->get_available_variations();
		foreach($variations as $variation){
			 $variation_id = $variation['variation_id'];
			 $variation_obj = new WC_Product_variation($variation_id);			 
			 if($product->get_stock_status() == 'outofstock'){
				echo 'Out of stock variation product ID: '.$variation_id .' link: '.get_permalink( $product->ID ).' Title: '.$variation_obj->get_title().'<br>';
			}
		}
    }	
	 
endwhile; wp_reset_query(); // Remember to reset 
echo 'stock update done';
?>

Убрать количество товара, оставив instock

Данный код уберет численные значения товара на складе, оставив просто instock

<?php
include( 'wp-load.php' );
// Setup your custom query
$args = [
    'post_type' => ['product'/*, 'post', 'page'*/],
    'posts_per_page' => -1,
    'post_status' => 'publish'
];
$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
	global $post;	
	$product = wc_get_product( $post->ID );		
	if($product->get_stock_quantity()>0 && $product->get_manage_stock() == 'yes' && $post->post_name != 'bra'){
		echo 'Update stock for simple product ID: '.$post->ID.' slug: '.$post->post_name.' Title: '.$product->get_title().' Old quantity: '.$product->get_stock_quantity().'<br>';
		// Using WC setters
        $product->set_manage_stock(false);
        $product->set_stock_quantity(0);
        $product->set_stock_status('instock');
        
        // Save Product
        $product->save();
	}
	 if ($product->get_type() == "variable" && $post->post_name != 'bra') {		
        $variations = $product->get_available_variations();
		foreach($variations as $variation){
			 $variation_id = $variation['variation_id'];
			 $variation_obj = new WC_Product_variation($variation_id);			 
			 if($variation_obj->get_stock_quantity()>0 && $variation_obj->get_manage_stock() == 'yes'){
				echo 'Update stock for variation product ID: '.$variation_id .' slug: '.$post->post_name.' Title: '.$variation_obj->get_title().' Old quantity: '.$variation_obj->get_stock_quantity().'<br>';
				// Using WC setters
				$variation_obj->set_manage_stock(false);
				$variation_obj->set_stock_quantity(0);
				$variation_obj->set_stock_status('instock');

				// Save Product
				$variation_obj->save();
			}
		}
    }	
	 
endwhile; wp_reset_query(); // Remember to reset 
echo 'stock update done';
?>

Создается отдельный php файл, к которому напрямую идет обращение из адресной строки браузера.

Получить количество товара в корзине

WC()->cart->get_cart_contents_count() – it allows to get a number of cart items including their quantity counts. For example, if you have 10 snowboards and 1 avocado toast in the cart, this method will return 11! You can see it yourself if you open this method in WooCommerce source code. It just gets the whole cart array from WC()->cart->get_cart() and then for each item it gets its quantity parameter.
count( WC()->cart->get_cart() ) – this implementation actually returns the number of unique products in the cart, one per product.

Woocommerce вывести ниже цену

Если для простых товаров нужно опустить цену ниже рейтинга в summary:

add_action('woocommerce_single_product_summary', 'move_single_product_price', 1);
function move_single_product_price() {
    remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
    add_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 29);
}

woocommerce product feed мультиязычность и мультивалютность

Если для создания фидов на сайте используется платный плагин woocommerce google product feed и необходимо создать разные фиды для разных языков и валют, то делается это с помощью адреса фида.

Никаких настроек для этого сам плагин фида, как и плагины мультиязычности/мультивалютности не содержит.

Фид достаточно создать в админке сайта только один. И для получения необходимого менять его адрес.

https://test.com/nl/woocommerce_gpf/844593872066e694dd6/?wmc-currency=EUR

где приставка /nl/ говорит о том, что в фид нужно включить товары на Нидерландском языке, ?wmc-currency=EUR в конце задает валюту фида.
Таким образом, можно создать фиды на разных языках с разной валютой.
В конце адреса не нужно ставить наклонную черту. Иначе нельзя будет получить через $_GET значение параметра wmc-currency.