Archives: Snippets | Page 13

Restrict File Upload Types in WordPress

The following example will restrict file uploads in the media library to JPG and GIF files only. If you want to also allow PNG files, add the line 'png' => 'image/png' to this code:

function savvy_restrict_mime($mimes) {
    $mimes = array(
        'jpg|jpeg|jpe' => 'image/jpeg',
        'gif' => 'image/gif',
    );
    return $mimes;
}
add_filter('upload_mimes','savvy_restrict_mime');

More on this topic in the post How to allow uploading additional file types in WordPress?.

Add Read More Link to Post Excerpt

If you want to add a link to the full post at the end of the post excerpt, you can do it like this. Add the following code to your functions.php file:

function savvy_excerpt_link_post($text) {
    return str_replace( '[...]', '<a href="'. get_permalink( get_the_ID() ) . '" title="' . esc_attr( get_the_title( get_the_ID() ) ) . '">' . '[&hellip;]' . '</a>', $text );
}
add_filter('the_excerpt', 'savvy_excerpt_link_post');

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

Remove All Sale Prices in WooCommerce

Want to hide sale prices on your products? Here is a way to remove all product sale prices on WooCommerce sites. Add the code to your child theme functions.php file:

/**
 * Savvy Disable all sales on WooCommerce Stores.
 *
 */
function savvy_wc_get_sale_price( $sale_price, $product ) {
	return $product->get_regular_price(); // Un-comment this to disable all sale prices
}
add_filter( 'woocommerce_product_get_sale_price', 'savvy_wc_get_sale_price', 50, 2 );
add_filter( 'woocommerce_product_get_price', 'savvy_wc_get_sale_price', 50, 2 );

Set Permalink Structure from functions.php

I do not see a reason you would want to do this, but you can set the WordPress permalink structure via code. To do this, add the following code to your theme’s functions.php file and change the permalink structure as needed:

function set_permalink(){
     global $wp_rewrite;
     $wp_rewrite->set_permalink_structure('/%year%/%monthnum%/%postname%/');
}
add_action('init', 'set_permalink');

Note that mod_rewrite must be active on the server in this case as well.

More on WordPress permalink structure in this post: Choosing the best permalink structure for SEO.

Add Tracking Code to WooCommerce Thank You Page

The following code lets you add tracking code to the WooCommerce Thank You page after a purchase. The $order variable contains all the relevant information for that order so you can send the details to the tracking service you use.

Pay attention to the comments in the code to understand where to add the tracking code and how to use this variable:

/**
 * Add custom tracking code to the thank-you page
 */

function my_custom_tracking( $order_id ) {

	// Lets grab the order
	$order = wc_get_order( $order_id );

	/**
	 * Put your tracking code here
	 * You can get the order total etc e.g. $order->get_total();
	 */
	 
	// This is the order total
	$order->get_total();
 
	// This is how to grab line items from the order 
	$line_items = $order->get_items();

	// This loops over line items
	foreach ( $line_items as $item ) {
  		// This will be a product
  		$product = $order->get_product_from_item( $item );
 
  		// This is the products SKU
		$sku = $product->get_sku();
		
		// This is the qty purchased
		$qty = $item['qty'];
		
		// Line item total cost including taxes and rounded
		$total = $order->get_line_total( $item, true, true );
		
		// Line item subtotal (before discounts)
		$subtotal = $order->get_line_subtotal( $item, true, true );
	}
}
add_action( 'woocommerce_thankyou', 'my_custom_tracking' );

Widen Address Fields in WooCommerce

Add the following code to your child theme functions.php file to make the address field wider:

/**
 * Make the billing address fields wider
 */

function custom_woocommerce_billing_fields( $fields ) {

     $fields['billing_address_1']['class'] = array( 'form-row-wide' );
     $fields['billing_address_2']['class'] = array( 'form-row-wide' );

     return $fields;
}
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');

Auto Complete Orders in WooCommerce

You can mark every order as completed automatically by adding the following code to your functions.php file. You can also change Completed to Processing to make every order processing automatically:

/**
 * Auto Complete all WooCommerce orders.
 */
function custom_woocommerce_auto_complete_order( $order_id ) {
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );
}
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );

For more WooCommerce hooks, see Mastering WooCommerce Hooks.

Show WooCommerce Checkout When Cart Is Empty

By default, there is an automatic redirect from the WooCommerce checkout page to the (empty) cart page when there are no products in the cart.

Try accessing the checkout page (link in footer) at this sample store and you will see the redirect.

There are uncommon situations where you may want to disable this redirect and show the user the checkout page anyway. You can do this by adding the following code to your functions.php file:

add_filter( 'woocommerce_checkout_redirect_empty_cart', '__return_false' );
add_filter( 'woocommerce_checkout_update_order_review_expired', '__return_false' );

Disable Yoast SEO Schema and Structured Data

Yoast SEO adds a JSON-LD schema graph to every page, built from your plugin settings. To disable Yoast schema output completely, return false on the wpseo_json_ld_output filter. Recent Yoast versions also have a settings toggle that does the same thing.

You’d do this when a theme, a dedicated schema plugin or hand-written JSON-LD already covers your structured data, and Yoast’s graph creates duplicates.

If you only want to drop the breadcrumb markup, see remove Yoast breadcrumbs schema. To change the trail itself, see add a link to Yoast SEO breadcrumbs.

The Code

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

add_filter( 'wpseo_json_ld_output', '__return_false' );

How It Works

Yoast applies wpseo_json_ld_output right before it prints the <script type="application/ld+json" class="yoast-schema-graph"> block. If the filter returns false or an empty array, Yoast prints nothing.

That removes the entire graph: Organization or Person, WebSite, WebPage, Article, BreadcrumbList, and the schema from Yoast’s FAQ and How-to blocks. Titles, meta descriptions and Open Graph tags are separate outputs and stay in place.

A named function that returns an empty array works too, since Yoast treats false and [] the same way. __return_false is just shorter.

To disable schema only on certain pages, return false conditionally and pass the original value through everywhere else:

add_filter( 'wpseo_json_ld_output', function( $data ) {
	if ( is_page( 'contact' ) ) {
		return false;
	}
	return $data;
} );

Disable Yoast Schema Without Code

Yoast SEO 26.8 added a Schema settings page. Go to Yoast SEO > Settings > Advanced > Schema and switch off Enable Schema Framework. On the front end, that adds the same __return_false filter shown above.

Yoast strongly recommends keeping the toggle on. Only turn it off when another tool fully replaces the graph, because without structured data the way your pages appear in search results can change.

If the toggle shows as off and switching it on gives the message “Yoast Schema Framework can’t be enabled”, some code already returns false or an empty array on wpseo_json_ld_output.

It may be your theme, a plugin or an old snippet. To find it, search your wp-content folder:

grep -rn "wpseo_json_ld_output" wp-content/

Remove that filter, or make it conditional, and the toggle works again.

Remove Only Part of the Schema

Many “Yoast broke my schema” problems are really duplicates: another plugin also outputs an Article or BreadcrumbList. You can drop just the overlapping piece and keep the rest of the graph.

Every piece has a wpseo_schema_needs_<identifier> filter. The identifiers are article, webpage, main_image, breadcrumb, website, organization, person, author, faq and howto.

// Keep Yoast's graph but drop its Article piece.
add_filter( 'wpseo_schema_needs_article', '__return_false' );

Other pieces may still reference the one you removed by @id. Check the output in the Rich Results Test, and for breadcrumbs use the full snippet on the breadcrumbs page linked above.

For more ways to adjust Yoast’s output, see Yoast SEO filters and the Yoast Schema API docs.

FAQs

Common questions about disabling Yoast SEO schema:

Does disabling Yoast schema affect my SEO titles and meta descriptions?
No. The wpseo_json_ld_output filter and the Schema toggle only remove the JSON-LD block. Titles, meta descriptions, canonicals, robots and social tags are output separately and keep working.
Do I need to uninstall Yoast SEO to get rid of its schema?
No, the filter or toggle is enough. If you do uninstall the plugin, note that deleting it leaves its data (the wp_yoast_ tables, options and post meta) in the database, so reinstalling restores your settings.
Is the Wincher integration related to Yoast schema?
No. Wincher is a keyphrase rank tracker and adds nothing to your structured data. To turn it off, go to Yoast SEO > Integrations and switch off the Wincher toggle.
I added the filter but the schema is still there. What's wrong?
Usually a page cache is serving the old HTML, so purge it and view the source again. If JSON-LD is still there, check its class: anything without yoast-schema-graph comes from another plugin or the theme.

Display Relative Dates in WordPress

Instead of displaying the exact date your post was published, you can display it relatively – “6 months ago” or “3 weeks ago”. Use the following code to do this:

# For posts & pages #
<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

# For comments #
<?php echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago'; ?>

For another useful date/time display, see Display Estimated Post Reading Time.