Archives: Snippets | Page 19

Change Number of Products Per Page in WooCommerce

Use the following code to change the number of products WooCommerce displays per page. For this to work, make sure the “Products per page” option is selected in Customizer.

Changing the number of products displayed per page

Add this code to your theme’s functions.php file:

/**
 * Change number of products that are displayed per page (shop page)
 */
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );

function new_loop_shop_per_page( $cols ) {
  // $cols contains the current number of products per page based on the value stored on Options –> Reading
  // Return the number of products you wanna show per page.
  $cols = 9;
  return $cols;
}

For more WooCommerce customization, see Mastering WooCommerce Hooks.

Completely Disable Search in WordPress

To completely disable WordPress search, add the following code to your theme’s functions.php file:

<?php function sv_filter_query($query, $error = true) {
    if (is_search()) {
        $query->is_search = false;
        $query->query_vars[s] = false;
        $query->query[s] = false;
        if ($error == true)
            $query->is_404 = true;
    }
}

add_action('parse_query', 'sv_filter_query');
add_filter('get_search_form', create_function('$a', "return null;"));
    
function remove_search_widget() {
    unregister_widget('WP_Widget_Search');
}

add_action('widgets_init', 'remove_search_widget');

Limit WordPress Search to Specific Post Types

Ever wondered how to limit search results to a specific Custom Post Type? It is simple. We have already seen how to completely disable WordPress search by modifying functions.php. Now we will do something similar to filter our search results.

Add the following code to your functions.php file:

function sv_search_filter($query) {
 
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('post','page'));
    }
 
return $query;
}
 
add_filter('pre_get_posts','sv_search_filter');

Note this line:

$query->set('post_type',array('post','page'));

You can filter search results by changing the values in that array. Search results will now show only pages and posts, but you can change this array to include any post type you want.

Show Only Free Shipping in WooCommerce Cart and Checkout

By default, WooCommerce displays all shipping options on the cart and checkout pages. If you want to show only the free shipping option on these pages, add the following code to functions.php:

/**
 * Hide shipping rates when free shipping is available.
 * Updated to support WooCommerce 2.6 Shipping Zones.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 * @link https://docs.woocommerce.com/document/hide-other-shipping-methods-when-free-shipping-is-available/
 */
function prefix_hide_shipping_when_free_is_available( $rates ) {
	$free = array();
	foreach ( $rates as $rate_id => $rate ) {
		if ( 'free_shipping' === $rate->method_id ) {
			$free[ $rate_id ] = $rate;
			break;
		}
	}
	return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'prefix_hide_shipping_when_free_is_available', 100 );

Multiple Excerpt Lengths in WordPress

You may or may not know that you can change or set the excerpt length in WordPress using the following filter:

function sv_excerpt_length( $length ) {
    return 15;
}
add_filter( 'excerpt_length', 'sv_excerpt_length' );

But that sets one excerpt length every time you use the the_excerpt function. What if you want different excerpt lengths in different places in your theme? In that case, you can use the following code in functions.php:

function excerpt($limit) {
      $excerpt = explode(' ', get_the_excerpt(), $limit);

      if (count($excerpt) >= $limit) {
          array_pop($excerpt);
          $excerpt = implode(" ", $excerpt) . '...';
      } else {
          $excerpt = implode(" ", $excerpt);
      }

      $excerpt = preg_replace('`[[^]]*]`', '', $excerpt);

      return $excerpt;
}

Then you can set the excerpt length in your theme like this:

<?php echo excerpt(25); ?>

Dismiss ACF Unsafe HTML Notice

The ACF plugin in version 6.2.5 and above displays a message like this: ACF now automatically escapes unsafe HTML when rendered by the_field or the ACF shortcode. If you know your field content is safe and want to dismiss this message, add the following code to your functions.php file:

function savvy_acf_remove_msg() {
	add_filter('acf/admin/prevent_escaped_html_notice', '__return_true');
	add_filter('acf/shortcode/allow_unsafe_html', '__return_true');
	add_filter('acf/the_field/allow_unsafe_html', '__return_true');
}
add_action('init', 'savvy_acf_remove_msg');

Disable WordPress URL Guessing

URL Guessing is a built-in WordPress feature that attempts to perform automatic redirects when a user lands on an incorrect URL. In other words, WordPress tries to guess the URL and redirects the user to an address similar to the wrong one entered in the browser bar, so instead of getting a 404 page, the user is redirected to the address WordPress thinks they meant.

To disable this feature, add the following code to your theme’s functions.php file:

<?php

function sv_no_redirect_404($redirect_url)
{
	if (is_404()) {
		return false;
	}
	return $redirect_url;
}
add_filter('redirect_canonical', 'sv_no_redirect_404');

Remove Yoast Breadcrumbs Schema

The Yoast SEO plugin adds a BreadcrumbList piece to its schema graph on every page. To remove the Yoast breadcrumbs schema and keep the rest of the graph, you need two filters: one drops the piece, the other removes its reference from WebPage.

This is useful when your theme or another plugin already outputs BreadcrumbList markup and Google Search Console reports duplicates, or when the trail doesn’t match your real site structure.

To switch off all of Yoast’s structured data instead, see disable Yoast SEO schema. To change the trail instead of removing it, see add a link to Yoast SEO breadcrumbs.

The Code

Add this snippet to your theme’s functions.php file (preferably in a child theme) or to a custom plugin:

add_filter( 'wpseo_schema_graph_pieces', 'remove_breadcrumbs_from_schema', 11, 2 );
add_filter( 'wpseo_schema_webpage', 'remove_breadcrumbs_property_from_webpage', 11, 1 );

/**
 * Removes the breadcrumb graph pieces from the schema collector.
 *
 * @param array  $pieces  The current graph pieces.
 * @param string $context The current context.
 *
 * @return array The remaining graph pieces.
 */
function remove_breadcrumbs_from_schema( $pieces, $context ) {
    return array_filter( $pieces, function( $piece ) {
        return ! $piece instanceof \Yoast\WP\SEO\Generators\Schema\Breadcrumb;
    } );
}

/**
 * Removes the breadcrumb property from the WebPage piece.
 *
 * @param array $data The WebPage's properties.
 *
 * @return array The modified WebPage properties.
 */
function remove_breadcrumbs_property_from_webpage( $data ) {
    if ( array_key_exists( 'breadcrumb', $data ) ) {
        unset( $data['breadcrumb'] );
    }
    return $data;
}

How It Works

wpseo_schema_graph_pieces receives the list of generator objects Yoast will run for the current page. The first function filters out the one whose class is Yoast\WP\SEO\Generators\Schema\Breadcrumb, so the BreadcrumbList is never built.

The WebPage piece still carries a breadcrumb property pointing to #breadcrumb by @id. wpseo_schema_webpage lets you edit that piece, and the second function deletes the property so the graph has no reference to a piece that no longer exists.

The code applies to every page on the site. Run both filters together: removing only one leaves either a duplicate BreadcrumbList or a broken reference.

Why the Snippet Didn’t Work

The most common cause is a class name that lost its backslashes when it was copied or saved (YoastWPSEOGeneratorsSchemaBreadcrumb). PHP doesn’t throw an error when instanceof checks against a class that doesn’t exist. It just returns false, so nothing is removed. Copy the code again from above.

If you paste the snippet through a tool that strips backslashes, use this shorter version instead. It removes the same markup through the wpseo_schema_needs_breadcrumb filter and has no class name at all:

add_filter( 'wpseo_schema_needs_breadcrumb', '__return_false' );

add_filter( 'wpseo_schema_webpage', function( $data ) {
    unset( $data['breadcrumb'] );
    return $data;
} );

Still seeing it? Purge your page cache, then view the page source and search for BreadcrumbList. If the match isn’t inside the yoast-schema-graph script, another plugin or your theme is adding it.

Schema vs. Visible Breadcrumbs

This snippet removes only the structured data. The breadcrumb trail your visitors see is a separate output, and it stays.

It works the other way too. Turning off Enable breadcrumbs for your theme under Yoast SEO > Settings > Advanced > Breadcrumbs doesn’t remove the BreadcrumbList schema, because Yoast builds that piece regardless of the setting.

To hide the visible trail, remove the yoast_breadcrumb() call, the Savvy / Snippets / Page 19 shortcode or the breadcrumbs block from your templates.

For other ways to display breadcrumbs, including without a plugin, see how to add breadcrumbs navigation to a WordPress site. The original snippet comes from the Yoast Schema API documentation.

FAQs

Common questions about removing Yoast’s breadcrumb schema:

Will removing breadcrumb schema hurt my SEO?
Google uses breadcrumb markup to understand where a page sits in your site, so don't remove it without a reason. Do it when something else already outputs correct BreadcrumbList markup, or when Yoast's trail is wrong and you can't fix it.
Can I remove the breadcrumb schema on specific pages only?
Yes. Add a condition such as is_front_page() or is_singular( 'product' ) to both callbacks and return the original value when it doesn't match. Keep the two conditions identical.
What is the wpseo_schema_webpage filter?
It's one of Yoast's wpseo_schema_<identifier> filters. It receives the WebPage piece as an array before output, so you can add, change or remove properties like breadcrumb.
Does this also hide the breadcrumbs on my pages?
No. It only removes the JSON-LD. The visible trail comes from yoast_breadcrumb(), the shortcode or the block in your theme, and you remove it there.