Archives: Snippets | Page 12

Redirect to Checkout After Adding Product in WooCommerce

WooCommerce can redirect to the cart after add to cart out of the box, but it has no setting to redirect to checkout after add to cart. For that you need the woocommerce_add_to_cart_redirect filter.

Skipping the cart makes sense for stores that sell one product at a time, such as courses, subscriptions or event tickets. Below are the code, the related setting, and the AJAX buttons that often make the redirect look broken.

Redirect to Checkout After Add to Cart

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

/**
 * Send customers straight to checkout after adding a product to the cart.
 */
function savvy_add_to_cart_redirect_checkout( $url ) {
    return wc_get_checkout_url();
}
add_filter( 'woocommerce_add_to_cart_redirect', 'savvy_add_to_cart_redirect_checkout' );

Then go to WooCommerce > Settings > Products and tick Redirect to the cart page after successful addition under “Add to cart behaviour”. The next section explains why the setting matters.

How It Works

When a product is added through a regular form submit or an ?add-to-cart= link, WooCommerce passes the redirect URL through woocommerce_add_to_cart_redirect. If the filter returns a URL, WooCommerce redirects there, whatever the setting says.

The filter also receives the product being added as a second argument. That lets you redirect only for some products, as shown below.

Older tutorials use WC()->cart->get_checkout_url(). That method has been deprecated since WooCommerce 2.5. It still works, but it triggers a deprecation notice and simply calls wc_get_checkout_url(), so use the function directly.

AJAX Add to Cart and the Redirect Setting

Shop and category pages usually add products with AJAX, controlled by Enable AJAX add to cart buttons on archives.

An AJAX request never reaches the redirect code in PHP, which is why the filter alone often seems to do nothing on archives.

WooCommerce handles this with the redirect setting:

  • Setting off: archive buttons add the product in the background and stay on the page. Your filter only affects single product pages and add to cart links.
  • Setting on: after the AJAX request succeeds, the script redirects to the cart URL, and that URL also goes through woocommerce_add_to_cart_redirect. With the snippet active, the result is checkout.

In block themes, the Product Button and Add to Cart with Options blocks switch to a regular link or form submit when the setting is on, so they go through the filter too.

Ticking the setting is what makes the redirect consistent across every button.

Redirect Only for Specific Products

Use the product argument to limit the redirect. This version skips the cart only for products in a courses category:

function savvy_add_to_cart_redirect_courses( $url, $product ) {
    if ( $product instanceof WC_Product && has_term( 'courses', 'product_cat', $product->get_id() ) ) {
        return wc_get_checkout_url();
    }
    return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'savvy_add_to_cart_redirect_courses', 10, 2 );

The instanceof check matters. When WooCommerce builds the cart URL for its AJAX script, it calls the filter with null instead of a product.

If a link adds a variation ID directly, $product is the variation, so check its get_parent_id() instead.

To show a message on the same page instead of redirecting, see Show a Message After Product is Added to Cart in WooCommerce. For more on the actions and filters involved, see Mastering WooCommerce Hooks: A Complete Guide.

FAQs

Common questions about redirecting to checkout after add to cart:

Is there a WooCommerce setting to redirect to checkout after add to cart?
No. The built-in setting under WooCommerce > Settings > Products only redirects to the cart. To land on checkout, combine that setting with the woocommerce_add_to_cart_redirect filter.
Why does the redirect work on product pages but not on the shop page?
Shop page buttons use AJAX, which does not run the PHP redirect. Enable "Redirect to the cart page after successful addition" and WooCommerce will send AJAX adds to the filtered URL as well.
Does the filter change the View cart link?
Yes, on classic archives. The "View cart" link that appears after an AJAX add uses the same filtered URL, so with the redirect setting off it points to checkout.
Will this work with Ajax add to cart on single product pages?
Not automatically. Custom AJAX on the single product form bypasses the PHP redirect, so the script must redirect itself after the request succeeds.

Increase Maximum Execution Time in WordPress

“Maximum execution time of 30 seconds exceeded” means a PHP script ran longer than the max_execution_time setting allows. In WordPress it usually hits during updates, imports and backups.

Below are the ways to increase max_execution_time and how to tell which one your server honors. For a quick fix of the error itself, see Fix Maximum Execution Time Exceeded in WordPress.

Check the Current Value First

Go to Tools > Site Health > Info and open the Server section.

  • PHP time limit is the current max_execution_time in seconds.
  • PHP SAPI tells you which method will work: apache2handler is Apache mod_php, fpm-fcgi is PHP-FPM, litespeed is LiteSpeed.

Recheck this screen after each change to confirm PHP picked up the new value.

Increase max_execution_time in WordPress

Pick the method that matches your PHP SAPI. The examples use 300 seconds, the limit WordPress core sets for itself during updates.

1. wp-config.php (works on any server)

Add this to wp-config.php, above the /* That's all, stop editing! */ line:

if ( function_exists( 'set_time_limit' ) ) {
	set_time_limit( 300 );
}

Keep the function_exists() check. Since PHP 8, a function blocked with disable_functions counts as undefined, so a bare call crashes the site on hosts that disable it.

2. .user.ini (PHP-FPM and CGI)

On PHP-FPM, the most common setup today, create a .user.ini file next to wp-config.php:

max_execution_time = 300
max_input_time = 300

PHP rereads this file every 5 minutes by default (user_ini.cache_ttl), so the change may not show immediately.

3. .htaccess (Apache mod_php or LiteSpeed)

Back up .htaccess first, then add this line:

php_value max_execution_time 300

This only works with Apache mod_php or LiteSpeed. On Apache with PHP-FPM, php_value is an unknown directive and the site returns a 500 error, so remove it and use .user.ini.

4. php.ini (VPS or dedicated server)

If you control the server, set it in php.ini and restart PHP-FPM or Apache. On shared hosting, use the PHP settings screen in your control panel.

max_execution_time = 300

How max_execution_time Works

The directive caps how many seconds a script may run (30 by default). Calling set_time_limit() changes the limit at runtime and restarts the counter from zero.

On Linux, standard PHP builds count only the script’s own execution time. Database queries and remote API calls don’t count, so a request can run past 30 seconds without this error.

max_input_time is the separate limit for parsing request input such as POST data and uploads. Its default of -1 means it uses max_execution_time. It can’t be changed with set_time_limit() or ini_set(), only in .user.ini, .htaccess or php.ini.

When Raising the PHP Limit Isn’t Enough

If long requests still die after raising the limit, another layer is cutting them off, usually with a 502, 504 or 524 error.

  • PHP-FPM’s request_terminate_timeout kills the worker after a set time. It’s off by default, but many hosts enable it.
  • Nginx’s fastcgi_read_timeout defaults to 60 seconds.
  • Cloudflare returns a 524 if the origin doesn’t respond within 125 seconds on non-Enterprise plans.

Your host has to raise these. For one-off heavy jobs, use WP-CLI instead: on the command line max_execution_time defaults to 0, meaning no limit.

WP-Cron runs as a web request, so web limits apply. For long scheduled tasks, disable WP-Cron and use a real server cron job that runs wp cron event run --due-now.

See also Optimizing WordPress configuration with wp-config.php and the directive reference in the PHP manual.

FAQs

Common questions about the PHP time limit in WordPress:

What is the default max_execution_time in WordPress?
WordPress doesn't set a global value. It inherits the PHP setting, which defaults to 30 seconds, though many hosts use 60 to 300. Core raises the limit temporarily with set_time_limit() during updates.
Why doesn't php_value max_execution_time in .htaccess work?
php_value is only understood by Apache mod_php and LiteSpeed. On PHP-FPM it causes a 500 error. Check PHP SAPI in Site Health and use .user.ini if it says fpm-fcgi.
How do I increase max_input_time in WordPress?
Set max_input_time = 300 in .user.ini or php.ini, or php_value max_input_time 300 in .htaccess on mod_php. It can't be changed from wp-config.php because PHP doesn't allow it at runtime.
Can I set max_execution_time to 0?
Yes, 0 removes the PHP limit, but a stuck script can then hold a PHP worker until a server timeout kills it. A finite value like 300 is safer on a live site.

Remove WooCommerce Breadcrumbs on Specific Pages

If you are looking for a way to remove breadcrumbs on sites using WooCommerce, you can do it like this:

/**
 * Remove the breadcrumbs
 */
function savvy_remove_shop_breadcrumbs() {
    if (is_shop()) {

        remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20);
    }
}
add_action('init', 'savvy_remove_shop_breadcrumbs');

This code removes breadcrumbs on the main shop page but you can use any other condition for other page types.

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.

Display Tag Cloud in WordPress Templates

Although we see less and less use of tag clouds on WordPress sites, here is how to add one using code in WordPress templates. This is the same tag cloud that appears in the widgets area of the WordPress admin.

Add the following code where you want in your template and change the parameters as needed:

<?php wp_tag_cloud(array(
     'smallest' => 10, // size of least used tag
     'largest' => 18, // size of most used tag
     'unit' => 'px', // unit for sizing
     'orderby' => 'name', // alphabetical
     'order' => 'ASC', // starting at A
     'exclude' => 6 // ID of tag to exclude from list
     ));
?>

For more on tags and taxonomies, see Taxonomies in WordPress.

Show Post Thumbnails in RSS Feed

If you want to display the post featured image in the RSS feed (essential if you use RSS for Mailchimp for example), add the following code to your functions.php file:

// Put post thumbnails into rss feed
function savvy_feed_post_thumbnail($content) {
    global $post;
    if(has_post_thumbnail($post->ID)) {
        $content = '' . $content;
    }
    return $content;
}
add_filter('the_excerpt_rss', 'savvy_feed_post_thumbnail');
add_filter('the_content_feed', 'savvy_feed_post_thumbnail');