The WordPress Code Hack Bundle


This is a comprehensive collection of code snippets to customize your WordPress website with HTML, CSS, Javascript, and PHP code. All should work with PHP 8.0 or newer, and WordPress 5.8 or newer.

To avoid causing disruptions to the website’s source code, you can use Code Snippets – a handy-dandy plugin that allows code snippets to be run directly on the backend without directly modifying the theme files or the WordPress source code files.

For WooCommerce

Enabling/Disabling the city/postcode/ZIP fields

City field:

add_filter( 'woocommerce_shipping_calculator_enable_city', '__return_true' );

You can change “true” to “false” to enable/disable.

Postcode/ZIP field:

add_filter( 'woocommerce_shipping_calculator_enable_postcode', '__return_false' );

Disable the Payment Method if a coupon is applied and the total comes to $0

add_filter('woocommerce_available_payment_gateways', 'applied_coupons_hide_payment_gateways', 20, 1 );
function applied_coupons_hide_payment_gateways( $available_gateways){
    // Not in backend (admin)
    if( is_admin() ) 
        return $available_gateways;

    // If at least a coupon is applied
    if( sizeof( WC()->cart->get_applied_coupons() ) > 0 ){
        // Loop through payment gateways
        foreach ( $available_gateways as $gateway_id => $gateway ) {
            // Remove all payment gateways except BACS (Bank Wire)
            if( $gateway_id != 'bacs' )
                unset($available_gateways[$gateway_id]);
        }
    }

    return $available_gateways;
}

Get the chosen Shipping Method title by the ID

$rate_table = array();

$shipping_methods = WC()->shipping->get_shipping_methods();

foreach($shipping_methods as $shipping_method){
    $shipping_method->init();

    foreach($shipping_method->rates as $key=>$val)
        $rate_table[$key] = $val->label;
}

echo $rate_table[WC()->session->get( 'chosen_shipping_methods' )[0]];

Add Shipping rate based on Cart total

add_filter( 'woocommerce_package_rates', 'tl_shipping_on_price', 10, 2 );
function tl_shipping_on_price( $rates, $package ) {
 
    $total = WC()->cart->cart_contents_total;
	//echo $total;
    if( $total <= 500 ) {
 
        unset( $rates['flat_rate'] );
        unset( $rates['free_shipping'] );
 
    } elseif ( $total > 500 && $total < 1000 ) {
 
        unset( $rates['local_delivery'] );
        unset( $rates['free_shipping'] );
 
    } else {
		unset( $rates['local_delivery'] );
        unset( $rates['flat_rate'] );
	}
 
    return $rates;
}

Exclude Products from a certain category on the WooCommerce Shop page

function custom_pre_get_posts_query( $q ) {

    $tax_query = (array) $q->get( 'tax_query' );

    $tax_query[] = array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'clothing' ), // Don't display products in the clothing category on the shop page.
           'operator' => 'NOT IN'
    );

    $q->set( 'tax_query', $tax_query );

}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

Add Plus + and Minus – buttons to Product pages

// -------------
// 1. Show Buttons
  
add_action( 'woocommerce_before_add_to_cart_quantity', 'silva_display_quantity_minus' );
  
function silva_display_quantity_minus() {
   echo '<button type="button" class="minus" >-</button>';
}
add_action( 'woocommerce_after_add_to_cart_quantity', 'silva_display_quantity_plus' );
  

function silva_display_quantity_plus() {
   echo '<button type="button" class="plus" >+</button>';
}
 
// Note: to place minus @ left and plus @ right replace above add_actions with:
// add_action( 'woocommerce_before_add_to_cart_quantity', 'silva_display_quantity_minus' );
// add_action( 'woocommerce_after_add_to_cart_quantity', 'silva_display_quantity_plus' );
  
// -------------
// 2. Trigger jQuery script
  
add_action( 'wp_footer', 'silva_add_cart_quantity_plus_minus' );
  
function silva_add_cart_quantity_plus_minus() {
   // Only run this on the single product page
   if ( ! is_product() ) return;
   ?>
      <script type="text/javascript">
           
      jQuery(document).ready(function($){   
           
         $('form.cart').on( 'click', 'button.plus, button.minus', function() {
  
            // Get current quantity values
            var qty = $( this ).closest( 'form.cart' ).find( '.qty' );
            var val   = parseFloat(qty.val());
            var max = parseFloat(qty.attr( 'max' ));
            var min = parseFloat(qty.attr( 'min' ));
            var step = parseFloat(qty.attr( 'step' ));
  
            // Change the value if plus or minus
            if ( $( this ).is( '.plus' ) ) {
               if ( max && ( max <= val ) ) {
                  qty.val( max );
               } else {
                  qty.val( val + step );
               }
            } else {
               if ( min && ( min >= val ) ) {
                  qty.val( min );
               } else if ( val > 1 ) {
                  qty.val( val - step );
               }
            }
              
         });
           
      });
           
      </script>
   <?php
}

Stylize Plus + and Minus – buttons on Product pages

.single-product div.product form.cart .quantity {
   float: none;
   margin: 0;
   display: inline-block;
}

Show Product Short Description on Shop page

function display_excerpt_shop_page() {
	
	echo get_ecommerce_excerpt();
}

add_action( 'woocommerce_after_shop_loop_item_title', 'display_excerpt_shop_page', 40 );

function get_ecommerce_excerpt() {
	global $post;
    $limit = 14;
    $text = $post->post_excerpt;
    if (str_word_count($text, 0) > $limit) {
        $arr = str_word_count($text, 2);
        $pos = array_keys($arr);
        $text = substr($text, 0, $pos[$limit]) . '...';
        // $text = force_balance_tags($text); // may be you dont need this…
    }
    echo '<span class="excerpt"><p>' . $text . '</p></span>';
}

Change Product Color Hover

add_action( 'wp_head', function () { ?>
<style>

	/* write your CSS code here */
	
.woocommerce li.product:hover .entry-header h3, .woocommerce-page li.product:hover .entry-header h3,
.woocommerce li.product:hover .entry-header h3 a, .woocommerce-page li.product:hover .entry-header h3 a,
.woocommerce-page li.product:hover .entry-header .price>.amount{
    color: #000 !important;    
}

</style>
<?php } );

WordPress Admin

Top bar getting too long? Clean it up with this snippet:

function mytheme_admin_bar_render() {
    global $wp_admin_bar;
    // we can remove a menu item, like the Comments link, just by knowing the right $id
    $wp_admin_bar->remove_menu('comments');
    // or we can remove a submenu, like New Link.
    $wp_admin_bar->remove_menu('new-content');
    $wp_admin_bar->remove_menu('id-of-top-bar-button');
}
// and we hook our function via
add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' );

P.S.: Use the code inspector panel on your web browser to find the id of each top bar menu item.

Numerous plugins can slow your site down – especially in a locally hosted environment. Install the CPS Custom PHP Settings plugin and add this into the editor:

upload_max_filesize=1024M
post_max_size=1024M
memory_limit=1024M
max_execution_time=300
max_input_time=300
max_input_vars=3000
zlib.output_compression=On

Adjust the numerical values as necessary. M = Megabytes. The numbers for max_ indicate seconds.

Hope this is of help to my fellow WordPress website developers out there,

– Ahmad