Archives: Snippets | Page 15

Remove Product Content by Category in WooCommerce

The following code for example removes product images on the WooCommerce single product page only for products in the “Cookware” category. You can of course remove any content you want by using the WooCommerce hooks available to you.

/**
 * Remove product content based on category
 */
function remove_product_content() {
	// If a product in the 'Cookware' category is being viewed...
	if ( is_product() && has_term( 'Cookware', 'product_cat' ) ) {
		//... Remove the images
		remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
		// For a full list of what can be removed please see woocommerce-hooks.php
	}
}
add_action( 'wp', 'remove_product_content' );

Add Random Sorting to WooCommerce Catalog

The woocommerce_catalog_ordering() function prints the “Default sorting” dropdown above the product loop. To add your own option to it, such as random sorting, you need two filters: woocommerce_catalog_orderby for the label and woocommerce_get_catalog_ordering_args for the query.

The example below adds a Random option. The same pattern works for any orderby value that WP_Query supports.

Add a Random Sorting Option

Add this to your child theme’s functions.php file or to a custom plugin:

/**
 * Add a "Random" option to the catalog sorting dropdown
 * and to the default sorting choices in the Customizer.
 */
function savvy_catalog_orderby_random( $options ) {
    $options['random_list'] = __( 'Random', 'your-textdomain' );
    return $options;
}
add_filter( 'woocommerce_catalog_orderby', 'savvy_catalog_orderby_random' );
add_filter( 'woocommerce_default_catalog_orderby_options', 'savvy_catalog_orderby_random' );

/**
 * Turn the "random_list" value into WP_Query arguments.
 */
function savvy_catalog_ordering_args_random( $args, $orderby, $order ) {
    if ( 'random_list' === $orderby ) {
        $args['orderby'] = 'rand';
    }
    return $args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'savvy_catalog_ordering_args_random', 10, 3 );

Visit the shop page and pick “Random” from the dropdown. The URL gets ?orderby=random_list and the products come back shuffled.

How It Works

woocommerce_catalog_orderby filters the options array that woocommerce_catalog_ordering() renders. The key becomes the orderby value in the URL and the value is the label.

woocommerce_default_catalog_orderby_options filters the “Default product sorting” choices in Appearance > Customize > WooCommerce > Product Catalog. The Customizer validates against this list, so without it you cannot save Random as the default.

When the shop query runs, WC_Query::get_catalog_ordering_args() reads the value from the URL or the default setting. It splits the value on a hyphen (price-desc becomes price and DESC), then passes the result to woocommerce_get_catalog_ordering_args as $args, $orderby and $order.

Two details matter:

  • Use underscores in custom keys. A key like random-list would be split into random and LIST.
  • Compare against $orderby, not $_GET. The function is also called by the [products] shortcode and blocks with their own values, and the parameter reflects what is actually being sorted.

The woocommerce_catalog_ordering() Function

WooCommerce hooks woocommerce_catalog_ordering() to woocommerce_before_shop_loop at priority 30, right after the result count at 20. It loads the loop/orderby.php template, and only outputs when the loop is paginated and products will be shown.

These are the default options, before filters:

Key Label
menu_order Default sorting
popularity Sort by popularity
rating Sort by average rating
date Sort by latest
price Sort by price: low to high
price-desc Sort by price: high to low

The function then adjusts the list. It removes menu_order when the default sorting is set to something else, removes rating when reviews or star ratings are disabled, and on search results replaces menu_order with relevance.

There is no dedicated sorting shortcode. The dropdown appears in [products paginate="true"], and block themes render it with the Catalog Sorting block, which calls the same function.

For querying products in your own templates, see Properly Retrieve WooCommerce Products in Your Template.

Random Sorting and Pagination

ORDER BY RAND() reshuffles on every request. On page 2 some products from page 1 can appear again while others never show up.

WP_Query accepts a seeded RAND(x) since WordPress 4.5. A seed that changes once a day keeps the order stable across pages and page caches:

if ( 'random_list' === $orderby ) {
    $args['orderby'] = 'RAND(' . absint( gmdate( 'Ymd' ) ) . ')';
}

Random ordering also forces MySQL to sort the whole result set, which gets slow on catalogs with many thousands of products.

FAQs

Common questions about WooCommerce catalog ordering:

How do I remove the sorting dropdown in WooCommerce?
In classic themes, add remove_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30 ); to functions.php. In block themes, remove the Catalog Sorting block from the product catalog template.
How do I remove a default sorting option?
Filter woocommerce_catalog_orderby and unset() the key, for example unset( $options['popularity'] );, then return the array.
Why is my custom sorting option not showing?
The dropdown only renders on paginated product loops with products to display. Also check that your theme or a page builder is not printing its own sorting control instead of woocommerce_catalog_ordering().
Can I sort by a custom field?
Yes. Add the option with woocommerce_catalog_orderby, then in woocommerce_get_catalog_ordering_args set $args['meta_key'] to your field and $args['orderby'] to meta_value or meta_value_num. Products without that field drop out of the results.

Allow HTML in Category and Tag Descriptions

By default, WordPress strips most HTML from category and tag descriptions when you save them. Only a short list of inline tags survives, so headings, lists, images and paragraphs with classes disappear the moment you click Update.

That gets in the way when you use category pages as landing pages with real intro content, which is one of the easier ways to optimize category pages for SEO. The snippet below allows HTML in category, tag and custom taxonomy descriptions.

The Code

Add this code to your child theme’s functions.php file or to a custom plugin:

/**
 * Allow HTML in term (category, tag) descriptions
 */
foreach ( array( 'pre_term_description' ) as $filter ) {
	remove_filter( $filter, 'wp_filter_kses' );
	if ( ! current_user_can( 'unfiltered_html' ) ) {
		add_filter( $filter, 'wp_filter_post_kses' );
	}
}

foreach ( array( 'term_description' ) as $filter ) {
	remove_filter( $filter, 'wp_kses_data' );
}

How It Works

WordPress sanitizes term descriptions with two filters, and the snippet removes both. Learn more about adding and removing filters in WordPress Hooks Explained.

  • pre_term_description runs before the description is saved. Core attaches wp_filter_kses here, which strips everything except a few basic tags.
  • term_description runs when the description is displayed. In the admin only, core adds wp_kses_data, which would strip the HTML again in the terms list table.

The current_user_can( 'unfiltered_html' ) check keeps it safe. Users with that capability can save any HTML, just like in the post editor.

Everyone else who can edit terms gets wp_filter_post_kses, the allowlist WordPress uses for post content. Tags like <h2>, <ul> and <img> work but <script> doesn’t.

Don’t remove wp_filter_kses without adding the fallback. That would let any user who can edit terms save scripts that run for every visitor.

What Changes After You Add It

The filters apply to every taxonomy, so the snippet covers categories, tags, custom taxonomies and WooCommerce product categories.

Situation Allowed HTML
Default, all users a, abbr, acronym, b, blockquote, cite, code, del, em, i, q, s, strike, strong
With the snippet, users with unfiltered_html Any HTML
With the snippet, other users The post content allowlist

Keep three things in mind:

  • Old descriptions aren’t restored. HTML was stripped before it reached the database, so re-enter it after adding the code.
  • On multisite, only super admins have unfiltered_html. Site admins get the post allowlist. The same applies to everyone if DISALLOW_UNFILTERED_HTML is set in wp-config.php.
  • Your theme has to print the description. term_description(), the_archive_description() and the Term Description block all output the stored HTML. A theme that escapes the description will show the tags as text.

If you’re building your own taxonomies, see how to create and query custom taxonomies. The wp_filter_kses() reference documents the sanitizer this snippet replaces.

FAQs

Common questions about HTML in category and tag descriptions:

Why does WordPress remove HTML from category descriptions?
Core runs wp_filter_kses on pre_term_description for every user, including administrators. It's a security default, and it only keeps basic inline tags such as links, bold and italics.
Does this work for WooCommerce product categories?
Yes. pre_term_description and term_description run for every taxonomy, including product_cat and product_tag. On product archives WooCommerce prints the description through wp_kses_post(), so scripts are removed there even if an admin saved them.
Does this add a visual editor to the description field?
No. The field stays a plain textarea, and you type the HTML yourself. The snippet only stops WordPress from stripping it.

Auto Display First Post Image or Default Fallback Image

Say you want to use the featured image (post thumbnail) that WordPress provides, but you have an archive with many posts and it would take a long time to add that featured image to each of them.

For new posts you can use the featured image in the standard way, but for old posts you want to use the first image in the post content as the featured image, or a default image if there are no images in that specific post. Add the following code to functions.php:

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+?src=['"]([^'"]+)['"].*?>/i', $post->post_content, $matches);
  $first_img = $matches[1][0];

  if(empty($first_img)) {
    $first_img = "/path/to/default.png";
  }
  return $first_img;
}

And to use this inside the WordPress loop:

if ( get_the_post_thumbnail($post_id) != '' ) {

  echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
   the_post_thumbnail();
  echo '</a>';

} else {

 echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
 echo '<img src="';
 echo catch_that_image();
 echo '" alt="" />';
 echo '</a>';

}

For more on WordPress image handling, see Image Sizes in WordPress.

Add Category Name to body_class in WordPress

The body_class function helps add classes to the body tag, which usually contains information about what type of page is currently displayed, and allows you to style specific elements on that page by that specific class.

For some reason WordPress does not add a class describing which category (or categories) you are in on a single post page (e.g. single.php). To add the category name to that body tag, use the following code:

function sv_add_category_to_single($classes) {
    if (is_single() ) {
        global $post;
        foreach((get_the_category($post->ID)) as $category) {
            // add category slug to the $classes array
            $classes[] = $category->category_nicename;
        }
    }
    // return the $classes array
    return $classes;
}
add_filter('body_class','sv_add_category_to_single');

This uses the body_class filter. Learn more in WordPress Hooks Explained.

Get the Featured Image URL in WordPress

To get the featured image URL in WordPress, use get_the_post_thumbnail_url(). It returns just the image URL instead of a full <img> tag, which is what you need for a CSS background-image, an Open Graph tag or a JavaScript slider.

get_the_post_thumbnail() returns the complete image element, and it is the right choice when you want an <img> with srcset. For the URL alone, use the snippets below.

Get the Featured Image URL

Add this inside the WordPress loop, in a template such as single.php or a template part:

<?php
if ( has_post_thumbnail() ) {
    $thumb_url = get_the_post_thumbnail_url( get_the_ID(), 'large' );
    ?>
    <div class="post-hero" style="background-image: url('<?php echo esc_url( $thumb_url ); ?>');"></div>
    <?php
}
?>

The variable $thumb_url holds the URL of the current post’s featured image in the large size.

How It Works

get_the_post_thumbnail_url( $post, $size ) has been in core since WordPress 4.4 (see the function reference). Both parameters are optional:

  • $post: a post ID or WP_Post object. Defaults to the global post in the loop.
  • $size: any registered size name, such as thumbnail, medium, large or full, or an array of width and height. Defaults to post-thumbnail.

The function returns false when the post has no featured image, so check has_post_thumbnail() first.

If the size name is not registered, WordPress returns the original image URL. See How to Define New Image Sizes in WordPress for adding your own sizes.

To print the URL directly, the_post_thumbnail_url( 'large' ) echoes it already escaped. The Featured Image panel only appears in the editor when your theme declares add_theme_support( 'post-thumbnails' ) in functions.php.

Outside the Loop or by Post ID

Pass the post ID as the first argument when you are outside the loop, for example in a widget or a hook:

$thumb_url = get_the_post_thumbnail_url( 42, 'full' );

When you also need the image dimensions, get the attachment ID first and use wp_get_attachment_image_src():

$thumb_id = get_post_thumbnail_id( 42 );
$image    = wp_get_attachment_image_src( $thumb_id, 'large' );

if ( $image ) {
    list( $url, $width, $height ) = $image;
}

If you only need the URL from an attachment ID, wp_get_attachment_image_url( $thumb_id, 'large' ) is the shorter version.

Featured Image URL from the REST API

A post object from the REST API only includes featured_media, which is the attachment ID. Add _embed=wp:featuredmedia to get the image data in the same request:

fetch( '/wp-json/wp/v2/posts?_embed=wp:featuredmedia' )
    .then( ( response ) => response.json() )
    .then( ( posts ) => {
        posts.forEach( ( post ) => {
            const media = post._embedded?.[ 'wp:featuredmedia' ]?.[ 0 ];
            const url   = media?.source_url;                        // original image
            const large = media?.media_details?.sizes?.large?.source_url; // large size, if generated
            console.log( post.id, url, large );
        } );
    } );

Limiting _embed to one relation works since WordPress 5.4, as described in the REST API global parameters docs.

If you also use _fields, include _links and _embedded in the list, or the embed is skipped. For a full example, see Show Posts from another Blog using REST API.

FAQs

Common questions about getting the featured image URL in WordPress:

How do I get the full-size featured image URL?
Pass 'full' as the size: get_the_post_thumbnail_url( get_the_ID(), 'full' ). This returns the URL of the uploaded image instead of a resized copy.
Why does get_the_post_thumbnail_url return false?
The post has no featured image set, or the function is looking at a different post than you expect. Outside the loop the global post may not be the one you want, so pass the post ID explicitly.
What is the difference between get_the_post_thumbnail and get_the_post_thumbnail_url?
get_the_post_thumbnail() returns a complete <img> tag with srcset, alt and dimensions. get_the_post_thumbnail_url() returns only the URL string.
Where is source_url in the REST API response?
With _embed, it is at _embedded['wp:featuredmedia'][0].source_url. Resized versions are under media_details.sizes, each with its own source_url.

Add Class to next_posts_link and previous_posts_link

These functions, if you are not familiar, create links to the previous and next post. They have many options but not one that lets you add a class to the link. If you want to do that, add the following code to your functions.php file:

add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');

function posts_link_attributes() {
  return 'class="styled-button"';
}

For more on pagination, see Add Pagination to WordPress Templates.

Change Post Order in WordPress Archives

The simplest way to change the post order on the page that uses the archive.php file is to use the pre_get_posts hook. In this case you should make sure the query is the one you want to apply the change to.

Using the is_archive or is_post_type_archive condition should work in this case. Here is an example:

function sv_change_sort_order($query){
    if(is_archive()):
        //If you wanted it for the archive of a custom post type use: is_post_type_archive( $post_type )
        //Set the order ASC or DESC
        $query->set( 'order', 'ASC' );
        //Set the orderby
        $query->set( 'orderby', 'title' );
    endif;
}
add_action( 'pre_get_posts', 'sv_change_sort_order');

You may want to learn more about the WordPress template hierarchy if you are not sure what this means.

Alternatively, if you prefer a graphical way to manage the order, you can use the dedicated plugin – reordering custom post types in WordPress which offers a drag-and-drop interface directly in the dashboard.

Change the WordPress Search URL Query String

By default WordPress uses the "s" parameter as the query string to perform a site search. In some cases you may want to change this parameter to a different string. You can do this easily with the following function:

function change_search_url_rewrite() {
    if ( is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
        exit();
    }
}
add_action( 'template_redirect', 'change_search_url_rewrite' );

After adding this function, the search URL will be search/test instead of ?s=test

Add a Custom Dashboard Widget in WordPress

The following code adds a new widget to the WordPress Dashboard. You can of course set what content appears in this widget. Add this code to your theme’s functions.php file:


add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
    wp_add_dashboard_widget('custom_help_widget', 'Help and Support', 'custom_dashboard_help');
}

function custom_dashboard_help() {
    echo '&lt;p&gt;Lorum ipsum delor sit amet et nunc&lt;/p&gt;';
}

It looks like this:

Adding a new widget to the WordPress Dashboard

For safe theme customizations, see What Are Child Themes and How to Use Them.