Code snippets

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

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

Product catalog

Change “New” badge text

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

Change “SOLD OUT” badge text

add_filter('reycore/woocommerce/loop/sold_out_text', function(){
	return 'SOLD OUT';
});

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');

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;
	}
}

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 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');

Product page

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);

If you want to disable cropping, make sure to change $size['crop'] to 0.


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);

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);
});

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;
});
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
});

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);
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20);
add_filter('reycore/woocommerce/allow_mobile_gallery', '__return_false');

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');
add_filter( 'woocommerce_breadcrumb_defaults', function($args){
	if( is_product() ){
		$args['home'] = _x( 'Home', 'breadcrumb', 'rey-core' );
		return $args;
	}
},20);

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;
    }
}

Put a single product in catalog mode

Make sure to replace the product IDs with the ones you want.

add_filter( 'woocommerce_is_purchasable', function ( $status, $product ){

	$product_ids = [
		100,
		101,
		102,
	];

	if( $product && ($id = $product->get_id()) && in_array($id, $product_ids, true) ){
		return false;
	}

	return $status;
}, 10, 2);

Adding a “Buy now” button

This snippet will create a button next to the Add to cart one which when clicked, it will redirect straight to the checkout.

EDIT: This now is a built-in feature of Rey. Access Customizer > WooCommerce > Product page – Components and enable it there.

add_action('woocommerce_after_add_to_cart_button', function(){

	if( ! ($product = wc_get_product()) ){
		return;
	}

	$url = add_query_arg([
		'add-to-cart' => $product->get_id(),
		], wc_get_checkout_url()
	);

	printf('<a class="button alt" href="%s">Buy Now</a>', esc_url($url) );

}, 0);

Please make sure to replace the product ids or categories ids.

add_action( 'woocommerce_after_single_product_summary', function(){

	$product_ids_to_exclude = [
		100,
		101,
	];

	$categories_ids_to_exclude = [
		100,
		101
	];

	$product_types_to_exclude = [
		'giftcard',
	];

	if( ! ($product = wc_get_product()) ){
		return;
	}

	$product_id = $product->get_id();
	$should_hide = false;

	// make sure the current product, is not inside the products ids to exclude array
	if( in_array($product_id, $product_ids_to_exclude, true) ){
		$should_hide = true;
	}

	// make sure the current product, is not a specific product type
	if( in_array($product->get_type(), $product_types_to_exclude, true) ){
		$should_hide = true;
	}

	// check if current product has the category
	if( has_term($categories_ids_to_exclude, 'product_cat', $product_id) ){
		$should_hide = true;
	}

	if( $should_hide ){
		remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
	}

}, 0 );
add_filter('woocommerce_related_products', function($related_posts, $product_id, $args){

    $cats_array = [];

    $terms = wp_get_post_terms( $product_id, 'product_cat' );

    //Select only the category which doesn't have any children
    foreach ( $terms as $term ) {
        $children = get_term_children( $term->term_id, 'product_cat' );
        if ( empty($children) )
            $cats_array[] = $term->term_id;
    }

    global $wp_query;

    $meta_query[] = $wp_query->visibility_meta_query();
    $meta_query[] = $wp_query->stock_status_meta_query();

    return get_posts(array(
        'orderby'        => 'rand',
        'posts_per_page' => $args['limit'],
        'post_type'      => 'product',
        'meta_query'     => $meta_query,
        'post__not_in'   => $args['excluded_ids'],
        'fields'         => 'ids',
        'tax_query'      => [
            [
                'taxonomy'  => 'product_cat',
                'field'     => 'id',
                'terms'     => $cats_array
            ]
        ],
    ));

}, 10, 3);

Show the product weight in product catalog & product page

These snippets below will output the product weight value defined in the product’s options in the backend Shipping options eg: https://d.pr/i/Y4QW6t .

To change the unit from KG to something else, access WooCommerce > Settings > Products and change the Weight unit option eg: https://d.pr/i/vifOOf .

// Single Product Page
add_action('woocommerce_single_product_summary', function(){

	global $product;

	if( ! $product ){
		return;
	}

	if( ! ($weight = $product->get_weight()) ){
		return;
	}

	printf('<div class="custom-weight-field">Weight: %s%s</div>', $weight, get_option( 'woocommerce_weight_unit' ));

}, 5);

// Product Item in Catalog
add_action('woocommerce_shop_loop_item_title', function(){

	global $product;

	if( ! $product ){
		return;
	}

	if( ! ($weight = $product->get_weight()) ){
		return;
	}

	printf('<div class="custom-weight-field">Weight: %s%s</div>', $weight, get_option( 'woocommerce_weight_unit' ));

}, 5);

General

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
});

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] .

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')) ));
});

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);

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"]');
} );

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);

Cart panel, change “View Cart” button to “Continue shopping”

add_action('init', function(){

    if( ! class_exists('ReyCore_WooCommerce_MiniCart') ){
        return;
    }

    remove_action( 'woocommerce_widget_shopping_cart_buttons', [ReyCore_WooCommerce_MiniCart::getInstance(), 'shopping_cart_button_view_cart'], 10 );

    add_action( 'woocommerce_widget_shopping_cart_buttons', function(){

        echo '<a href="' . esc_url( get_permalink( wc_get_page_id('shop') ) ) . '" class="btn btn-secondary wc-forward button--cart">Continue Shopping</a>';

    }, 10 );

});

Add custom taxonomy for Product Grid element

First, try to get the Product Grid’s element ID. Here’s a quick recording how to do it https://d.pr/v/rSWPpM .

Replace $taxonomy_name with the taxonomy name.

Replace $terms_ids with the term ids you want to query. Usually you can find them in the link address ex: https://d.pr/i/xbC9LG .

Note: I want to point out that using WooCommerce Attributes is usually a better solution because it’s much more tied together with WooCommerce.


add_filter('reycore/elementor/product_grid/query_args', function($query_args, $element_id, $element_settings){

	// Change with the custom taxonomy name
	$taxonomy_name = 'custom_tax_name';

	// Change with Terms Ids
	$terms_ids = [
		100,
		200
	];

	// get the element ID (quick video how to get the element ID https://d.pr/v/rSWPpM )
	if( $element_id === 'ea7876c' ){
		$query_args['tax_query'][] = [
			'taxonomy'	=> $taxonomy_name,
			'field'		=> 'term_taxonomy_id',
			'terms'		=> $terms_ids,
			'operator' => 'IN',
		];
	}

	return $query_args;
}, 10, 3);
Was this article helpful?
Dislike 0
Views: 3741

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