Code snippets

You are here:
Estimated reading time: 5 min
In this article

Most of these codes should be pasted into wp-content/themes/rey-child/functions.php .

Show Wishlist icon on products when in Catalogue Mode

Catalogue mode* is when Ecommerce functionality is disabled.

add_action('wp', function(){
	if( class_exists('WooCommerce') && class_exists('TInvWL_Public_AddToWishlist') && is_product() ) {
		$product = wc_get_product();
		if( ! $product->is_purchasable() && ($product->get_regular_price() || $product->get_sale_price()) ) {
			add_action( 'woocommerce_single_product_summary', function(){
				echo do_shortcode("[ti_wishlists_addtowishlist]");
			}, 20 );
		}
	}
});

Force custom height & cropping in product page images

Replace 400 height with another size. It might be needed to regenerate, so you can try accessing WooCommerce > Status > Tools > Regenerate eg: https://d.pr/i/aKwJ8K .

add_filter('woocommerce_get_image_size_single', function($size){
  $size['width']  = absint( wc_get_theme_support( 'single_image_width', get_option( 'woocommerce_single_image_width', 600 ) ) );
  $size['height'] = 400;
  $size['crop']   = 1;
  return $size;
});

Or, if you want to have a strict aspect ratio such as the catalog thumbnails, here’s the custom code:

add_filter( 'woocommerce_get_image_size_single', function($size){
  $size['width']  = absint( wc_get_theme_support( 'single_image_width', get_option( 'woocommerce_single_image_width', 600 ) ) );
  $width_ratio    = max( 1, get_option( 'woocommerce_thumbnail_cropping_custom_width', '4' ) );
  $height_ratio   = max( 1, get_option( 'woocommerce_thumbnail_cropping_custom_height', '3' ) );
  $size['height'] = absint( Automattic\WooCommerce\Utilities\NumberUtil::round( ( $size['width'] / $width_ratio ) * $height_ratio ) );
  $size['crop']   = 1;
  return $size;
}, 20);


Replace 180 with another size. It might be needed to regenerate, so you can try accessing WooCommerce > Status > Tools > Regenerate eg: https://d.pr/i/aKwJ8K .

add_filter('woocommerce_get_image_size_gallery_thumbnail', function ($size){
	$cropping['width'] = max( 1, get_option( 'woocommerce_thumbnail_cropping_custom_width', '4' ) );
	$cropping['height'] = max( 1, get_option( 'woocommerce_thumbnail_cropping_custom_height', '3' ) );
	$size['width']  = 180;
	$size['height'] = ($cropping['height'] / $cropping['width']) * $size['width'];
	$size['crop']   = 1;
    return $size;
}, 10);

add_filter( 'woocommerce_breadcrumb_defaults', function($args){
	if( is_product() ){
		$args['home'] = _x( 'Home', 'breadcrumb', 'rey-core' );
		return $args;
	}
},20);

Slow Customizer? Disable the preview iframe.

add_action('customize_controls_print_footer_scripts', function(){
	?>
	<script>
		document.addEventListener('DOMContentLoaded', function(){
			document.getElementById('customize-preview').remove();
		});
	</script>
	<?php
});

Remove price from loop & product page

add_action('wp', function(){
    remove_action('reycore/woocommerce/after_shop_loop_item', 'woocommerce_template_loop_price', 10);
    remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_price', 60);
    remove_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);
    remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
});

Add WooCommerce Multilingual Currency Switcher into Default Header


// Adds the currency switcher in the header
add_action('rey/header/row', function(){

    // This shortcode adds the Currency switcher
    // but too much text is shown
    //echo do_shortcode('[currency_switcher]');

    // instead show only what matters
    do_action('wcml_currency_switcher', array(
        'format' => '%code% (%symbol%)'
    ));

}, 70);

And also some fine tuning CSS in Customizer > Additional CSS

.wcml_currency_switcher {
    margin-left: 1.5rem;
    width: auto;
}

These codes apply for the Default header, when it’s non Global Section. If you’re using a Header Global Section, simply add a Shortcode element into the Header section and paste the shortcode eg: [currency_switcher] .

Prevent opening cart panel on single product page, on mobiles

Add this code into rey-child/functions.php

add_action('wp_footer', function(){
	?>
	<script>
		jQuery(document).on('ready', function(){

			var $atcBtn = jQuery(".single_add_to_cart_button.button");

			var addPreventClass = function(){
				if( ! jQuery.reyHelpers.is_desktop ){
					$atcBtn.addClass('--prevent-open-cart');
				}
			};

			addPreventClass();

			jQuery(document).on("woocommerce_variation_has_changed", ".variations_form", function (e) {
				addPreventClass();
			});
		});
	</script>
	<?php
}, 999);

Change Add To Cart button bg-color in single product pages

.woocommerce div.product .rey-cartBtnQty {
  --accent-color: #cf2929;
}

add_action('wp_footer', function(){ ?>
	<script>
		(function($){
			$(document).on('ready', function(){
				$(document).on("check_variations", ".variations_form", function (e) {
					if( typeof $.fn.wc_variations_image_reset === 'function' ){
						$(this).wc_variations_image_reset();
					}
				});
			});
		})(jQuery);
	</script>
	<?php
});
add_filter('woocommerce_output_related_products_args', function($args){
	$args['posts_per_page'] = 3;
	$args['columns'] = 3;
	return $args;
}, 10);

Change “New” badge text

add_filter('reycore/woocommerce/loop/new_text', function(){
  return 'NEW ARRIVAL';
});

Change “New” badge duration time

By default it’s 30 days. In the example below you can override at 60 days.

add_filter('reycore/woocommerce/loop/new_badge/newness', function($duration){
	return 60;
}, 20);

Account header panel: Disable Ajax submitting forms in registration & login forms

add_filter('reycore/header/account/ajax_forms', '__return_false');
add_filter('reycore/woocommerce/account_links/register_btn_attributes', function(){
	return sprintf('href="%s"', esc_attr( get_permalink(wc_get_page_id('myaccount')) ));
});
add_filter('reycore/woocommerce/account_links/forget_btn_attributes', function(){
	return sprintf('href="%s"', esc_attr( get_permalink(wc_get_page_id('myaccount')) ));
});

Sticky Add to cart bar: Hide on specific products/categories

add_filter('theme_mod_product_page_sticky_add_to_cart', function( $status ){
	global $post;

	if( is_product() ) {

		/**
		 * This condition checks for product page having a specific ID.
		 * Replace "446" with a specific product ID you want to disable, or add more into the array, separated by comma
		 */
		if( in_array( $post->ID, [ 446, 407 ], true ) ){
			return false;
		}

		/**
		 * This condition checks for product having specific categories.
		 * Replace "t-shirts-tops" with a specific category slug you want to disable, or add more into the array, separated by comma
		 */
		if( has_term( [ 't-shirts-tops', 'some-other-category-slug' ], 'product_cat', $post ) ){
			return false;
		}

	}

	return $status;
});

ACF fields: Place custom data over the product thumbnail in product catalog

function custom__load_acf_field(){

	// bail if ACF doesn't exist
	if( ! class_exists('ACF') ){
		return;
	}

	// bail if not a product tax, or shop page
	if( ! (is_tax(get_object_taxonomies('product')) || is_shop()) ) {
		return;
	}

	global $post;

	if( $my_field = get_field('my_custom_field', $post) ){
		echo $my_field;
	}
}

add_action('reycore/loop_inside_thumbnail/top-left', 'custom__load_acf_field');

// Other hooks inside the thumbnail, in various corners:
// add_action('reycore/loop_inside_thumbnail/top-right', 'custom__load_acf_field');
// add_action('reycore/loop_inside_thumbnail/bottom-left', 'custom__load_acf_field');
// add_action('reycore/loop_inside_thumbnail/bottom-right', 'custom__load_acf_field');
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20);
add_filter('reycore/woocommerce/allow_mobile_gallery', '__return_false');

Fix for discounted price going off, on mobiles

@media (max-width: 767px) {
	.woocommerce ul.products li.product .price {
		flex-wrap: wrap;
	}
	.woocommerce ul.products li.product .price ins {
		flex-basis: 100%;
		margin-left: 0;
		margin-top: 10px;
	}
}

Apply “zero-px” hack for outdated minifiers in caching plugins

Some caching plugin css minifiers are trimming “0px” values and remove the unit, leaving it as “0” only. This breaks CSS variables and calc() functions in CSS. To prevent this, i made a “hack” until these minifiers will get updated to the latest browser standards. To enable it, use this code below.

add_action('wp_head', function(){
	?>
	<script>
		document.documentElement.style.setProperty('--zero-px', '0px');
	</script>
	<?php
}, 0);

Disable products from being purchased, but still show price

// Disable product with ID = 10, 11 from being purchased no matter what
add_filter('woocommerce_is_purchasable', function( $is_purchasable, $product ) {

	$products_ids = [ 10, 11 ];

	if( in_array($product->get_id(), $products_ids, true) ) {
		return false;
	}

	return $is_purchasable;
}, 10, 2 );

// Disable products from category "Uncategorized" from being purchased no matter what
add_filter('woocommerce_is_purchasable', function ( $is_purchasable, $product ) {

	$products_categories = [ 'uncategorized' ];

	if( has_term( $products_categories, 'product_cat', $product->get_id() ) ) {
		return false;
	}

	return $is_purchasable;
}, 10, 2 );

Add price suffix per products belonging to certain categories

add_filter( 'woocommerce_get_price_suffix', function ( $html, $product, $price, $qty ){

	$category_slugs = [
		'down-coats-vests',
		'sweatshirts-hoodies'
	];

	if( has_term( $category_slugs, 'product_cat', $product->get_id() ) ){
		$html .= '<span>per square</span>';
	}

    return $html;
}, 99, 4 );

Show a generic global section under Place order button in Checkout page

add_action('woocommerce_review_order_after_payment', function(){
	// replace 2700 with the global section id you want
	echo do_shortcode('[rey_global_section id="2700"]');
} );

Move Filter offcanvas panel on the left side of the screen

.rey-filterPanel-wrapper {
    left: 0;
    right: auto;
    transform: translateX(-100%);
}

@media (min-width: 1025px){
   .--filter-panel-active .rey-siteContent {
        transform: translateX(100px);
    }
}

Sticky Add to cart bar, add finish point

The bar will show up after the add to cart button has exited the viewport and will show up til the end of the page. If you want the bar to show up until a certain point, you can use this code below.

Either add a fixed number (eg 2000) or a css class selector.

add_filter('reycore/module/sticky_add_to_cart_settings', function($settings){

	// add a class of an element
	$settings['finish_point'] = '.related.products';

	// add a fixed value
	// $settings['finish_point'] = '2000';

	return $settings;
}, 20);

Add product page subtitle

You will need to make use of Advanced Custom Fields plugin. Here is a video explaining how to create a custom ACF field https://d.pr/v/MDSNIx .

And below is the code you need to add into the child theme’s functions.php to display the content.

add_action('woocommerce_single_product_summary', function(){
	global $product;
	if( class_exists('ACF') && $product && ($subtitle = get_field('prod_extra__subtitle', $product->get_id())) ){
		printf('<h4 class="product-subtitle">%s</h4>', $subtitle);
	}
}, 5);

Change product page’s Photoswipe lightbox theme to light mode

And below is the code you need to add into the child theme’s functions.php to display the content.

add_filter( 'rey/main_script_params', function($params){

	if( isset($params['js_params']['photoswipe_light']) ){
		$params['js_params']['photoswipe_light'][] = true;
	}

	return $params;
}, 20 );
add_filter('reycore/woocommerce/galleries/remove_title', '__return_true');

Product page, on mobiles, move breadcrumbs above the images

In the child theme’s functions.php please add this code:

add_action('init', function(){
    add_action( 'woocommerce_before_single_product_summary', 'woocommerce_breadcrumb', 5 );
});

In Customizer > Additional CSS add this style snippet to hide the default breadcrumb on mobiles and show the top one.

.summary > .rey-breadcrumbs {
    display: none;
}
@media (min-width: 1025px){
    .rey-productSummary > .rey-breadcrumbs {
        display: none;
    }
    .summary > .rey-breadcrumbs {
        display:block;
    }
}

Account panel, change the user’s display name

add_filter('reycore/woocommerce/account-menu/heading', function($content, $current_user){

    // user_login
    // user_nicename
    // display_name

    return sprintf( __('Hello %s,', 'woocommerce'), $current_user->user_login );

}, 20, 2);

Show product weight and dimensions in product items catalog list

add_action( 'woocommerce_after_shop_loop_item_title', function(){

	global $product;

	$dimensions = $weight = '';

	if ( $product && $product->has_dimensions() ) {
		$dimensions = wc_format_dimensions( $product->get_dimensions( false ) );
	}

	if ( $product && $product->has_weight() ) {
		$weight = wc_format_weight( $product->get_weight() );
	}

	if( $dimensions || $weight ){
		printf('<p class="loop-dimensions-weight"><small>%1$s / %2$s</small></p>',
			$dimensions,
			$weight
		);
	}

}, 15 );

Show tags list in product items catalog list

add_action( 'woocommerce_after_shop_loop_item_title', function(){

	global $product;

	if( ! $product ){
		return;
	}

	if( ! ( $tags_ids = $product->get_tag_ids() ) ){
		return;
	}

	echo wc_get_product_tag_list( $product->get_id(), ', ', '<p class="loop-tags"><small>' . _n( 'Tag:', 'Tags:', count( $tags_ids ), 'woocommerce' ) . ' ', '</small></p>' );

}, 15 );

Product catalog, add random sorting option

//add "Random" setting to product sorting menu
function rey_addRandomProductOrderSetting($sortby){
	$sortby['random_order'] = 'Random';
	return $sortby;
}
add_filter('woocommerce_default_catalog_orderby_options','rey_addRandomProductOrderSetting');
add_filter('woocommerce_catalog_orderby','rey_addRandomProductOrderSetting');

//randomize products when setting is used
function rey_randomizeProductWhenSet($args){

	$orderbySetting = isset($_GET['orderby']) ? wc_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));

	if('random_order' == $orderbySetting){

		if(false===($seed = get_transient('rey_randSeed'))){
			$seed = rand();
			set_transient('rey_randSeed', $seed, 3600 );
		}

		$args['orderby'] = 'RAND('.$seed.')';
		$args['order'] = '';
		$args['meta_key'] = '';
	}

	return $args;
}
add_filter('woocommerce_get_catalog_ordering_args','rey_randomizeProductWhenSet');
Was this article helpful?
Dislike 0
Views: 2778

9 Replies to “Code snippets”

  1. Eloy Bruckhoff

    Hi, is it possible to put the product title above the product gallery for mobile only?

    Desktop is great but I’d like to compact mobile in that way.

    1. mariushoria[ Post Author ]

      Hi Eloy,

      Unfortunately no, because the Title’s tag is inside another blocks eg: https://d.pr/i/YoQMyL . The only way could be by adding a new title tag before the mobile gallery tag and show it on mobiles only, while the Summary’s title will be hidden on mobiles. The problem here is that the title has an H1 tag and i’m not sure how this would perform in SEO terms.

  2. Kaye

    Is there a code snippet to change the URL for attributes linking when using AJAX filters?

    Currently my attribute links to domain.com/shop/attro-country=XX but for SEO purposes I would like to link to the attribute name like domain.com/shop/country=XX

    1. mariushoria[ Post Author ]

      Hi Kaye,

      No there isn’t, however i believe the issue is more complicated and usually filtered links either rely on robots.txt or canonicalization.

  3. Henrik Dalin

    Hey, Is there any string to display shopping cart amount like the picture instead of the normal counter?
    I see that it exists a string for “total” = {{total}}
    So it should exist one for item count in cart?

    https://gyazo.com/4e832ad53987a08970497fb9303b4398

    1. mariushoria[ Post Author ]

      Henrik, that’s a great idea. Noted for the upcoming update! Marius

  4. Kuba

    how can I override woocommerce templates which are in plugins/rey-core/woocommerce ? in child theme?

    1. mariushoria[ Post Author ]

      Hi Kuba,

      Sure, for example for a template file like this one plugins/rey-core/template-parts/woocommerce/template-file.php you can override them in wp-content/themes/rey-child/template-parts/woocommerce/template-file.php .

      Marius

  5. Kuba

    How to change upsell product code to be displayed in one row with carousel effect like related products? If You have more than 2 upsell products they are displayed in multiple rows on mobile.

    thanks

Join the conversation