WooCommerce Code Snippets


Remove Parent Theme Functions

Remove Parent Theme Functions - this comes in handy when working in a premium theme that you might want to update with new versions, but you want to make changes to it in a child theme.

Replace parent function

replace parent function with a function in a child theme. Overriding a parent function with a child function.

Remove unwanted Scripts and css

For when your parent theme contains scripts or css that you don't want or need...

Aqua Resizer

Resize images using aqua resizer. Aqua Resizer is a great little tool for when several images on a page must all be the same size. In a perfect world, we would just crop and resize in something like Photoshop, but the reality for a web developer is that not all of our clients have a photo editing tool and or have the skillset

query category

Pull category for each unique post using the ID and replace spaces and special characters. This comes in handy when using isotope.js to filter projects or portfolio items by category. https://isotope.metafizzy.co/. Note, if a category is more than one word or has a special character such as an '&' then see the bottom example.

Enqueue Parent Styles to Child Theme

making sure that the parent css still gets loaded into the child theme

Child Overwrite scripts and styles

add_action( 'wp_print_scripts', 'child_overwrite_scripts', 100 ); add_action( 'wp_print_styles', 'child_overwrite_styles', 100 ); function child_overwrite_scripts() { //wp_deregister_script( 'sydney-scripts' ); //wp_deregister_script( 'sydney-main' ); wp_deregister_script( 'comment-reply' ); } function child_overwrite_styles() { wp_deregister_style( 'sydney-font-awesome' ); wp_deregister_style( 'sydney-bootstrap' ); }

Remove Default Widgets

remove the default out of the box widgets that most of my clients never ever ever use

CMB2 repeatable fields groups

Using CMB2 to add repeating fields to a page or post - CMB2 has become one of my favorite plugins (even though it isn't officially known as a plugin). Using a repeatable field snippet from CMB2 is great for when you don't want to put a minimum or a maximum number of entry options for images, custom fields... I often use this in tandem with an Owl Carousel where I want my client to be able to add unlimited Testimonials, specials, gallery images, slider images...

foreach query for repeating fields group

get post meta from post_id or cpt_id and name of repeating field group. do a for each loop to pull meta data...

Querying a CPT

querying a custom post type - in this example we are querying the 'projects' post type

Displaying a CPT query

retrieving and displaying a queried cpt while loop

Add Post Thumbnail theme support to your CPTs

Add Post Thumbnail theme support to your CPTs

Complete Query with Output and endwhile

Complete project-page.php with get_header, while loop, output, and endwhile...

WP Nav Walker…

/*class My_Walker_Nav_Menu extends Walker_Nav_Menu { function start_lvl( &$output, $depth = 0, $args = array()) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"megamenu full-width\">\n"; } } $menuSettings = array( 'container' => 'div', 'menu_class' => 'jetmenu blue', //change this to whatever classes you need for your menu 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s list">%3$s</ul>', 'depth' => 3, //the number of submenus + 1 'walker' => new My_Walker_Nav_Menu() ); wp_nav_menu( $menuSettings ); //This script displays the menu. Please put it where you want it to display the menu.*/

modify nav menu args

//Add jetmenu blue class to the megamenu plugin function modify_nav_menu_args( $args ) { if( 'primary' == $args['theme_location'] ) { $args['menu_class'] = 'jetmenu blue'; } return $args; } add_filter( 'wp_nav_menu_args', 'modify_nav_menu_args', 20000 );

use-child-theme

facetwp use child theme

Set Default Images Link to NONE

set default image link location to 'None'

Always Show Kitchen Sink in WYSIWYG Editor

Always Show Kitchen Sink in WYSIWYG Editor

function to add an admin account

function to add an admin account via ftp and the functions.php file

posts carousel

<div id="blog" class="dark-version dark-section section-block"> <div class="container"> <div class="row"> <div class="mid-space"></div> <div class="col-sm-5 col-lg-8 col-lg-push-2 section-title-wrapper" style="padding:15px 60px; text-align: center;"> <h2 class="section-title-wrapper">Latest From the Blog</h2> </div> <div class="mid-space"></div> </div> <div class="row"> <!-- Latest Post 1 --> <div class="owl-carousel"> <?php $loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => -1, 'orderby'=> 'ASC')); ?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="grid post-entry" style="width:95%;"> <?php $postTitle = get_the_title(); $post_image = the_post_thumbnail(); $source_image = $post_image; // let's assume this image has the size 100x100px $width = 500; // note, how this exceeds the original image size $height = 400; // some pixel

Changing shipping options in WooCommerce based on Cart and Coupon

// If the cart total is greater than 250 dollars and none of the excluded coupons are applied then the user should get free shipping or pick up in the shop. Remove flat Rate // Here is the list of excluded coupons: $excluded_coupons = array('coupon1', 'coupon2', 'coupon3', 'coupon4', 'coupon5', 'coupon6', 'cooupon7', 'eight', 'nine', 'ten'); // If an excluded coupon is applied, then free shipping should no longer be an option. They should only get presented pickup in the shop or flat rate shipping. // If the cart is under 250 they get flat rate shipping or free pickup in the shop. // If a cart is over 250 and they use any other coupon, not in the excluded coupons array, the user should get free shipping or pickup in the shop. // So the only time Flat Rate should get presented is when the cart is under 250 or the user has applied a coupon in the Excluded coupons array. // free shipping should be an option to anyone with a cart over 250 and is not using an excluded coupon

.stylelingrc.json

initial set of rules used to get a passing css file

stylelint task for gulpfile.js

stylelint task for gulpfile.js

z-index bug in cssnano

.pipe(cssnano({zindex: false}))

New wp_query

$wallposts = new WP_Query( $args );

new WP_User_Query

$administrator_ids = new WP_User_Query( array( 'role' => 'administrator' ) ); $admins = $administrator_ids->get_results(); $admin_ids = array(); foreach($admins as $admin) { $admin_ids[] = $admin->ID; } $args2 = implode(',', $admin_ids); // echo $args2

array_merg

$friends_ids = UM()->Activity_API()->api()->friends_ids(); $friends_admin = array_merge($friends_ids, $admin_ids); if ( $friends_ids ) { $args['meta_query'][] = array( 'key' => '_user_id', 'value' => $friends_admin, 'compare' => 'IN' ); }

cURL

function CallAPI($method, $url, $data = false) { $curl = curl_init(); switch ($method) { case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_PUT, 1); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); } /* Optional Authentication: curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, "username:password"); */ curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result; }; $results = CallApi( 'GET', 'https://opensnow.com/publicapi/2.0/{Client Key}/locations/6'); $results = json_decode($results, true);

foreach on json data feed

foreach ( $results['0']['forecast']['daily'] as $daily ){ // date in a string format $date = $daily['date']; //Convert the date string into a unix timestamp. $unixTimestamp = strtotime($date); //return just the day full name of the day using PHP's date function. $dayOfWeek = date("l", $unixTimestamp); echo '<div class="column-fifth">'; echo 'Date: ' . $daily['date'] . '<br>'; echo '<p><strong>' . $dayOfWeek . ' Night</strong></p>'; echo '<img src="' . $daily['night']['icon'] . '" style="max-width:100px;"> <br>'; echo 'High: ' . $daily['night']['temp'] . '<br>'; echo 'Snow: ' . $daily['night']['snow'] . '<br>'; echo $daily['night']['weather'] . '<br>'; echo 'Wind Speed: ' . $daily['night']['wind']['speed'] . '<br>'; echo 'Wind Direction: ' .

js fetch api

var myList = document.querySelector('ul'); fetch('snowreport.json') .then(function(response) { if (!response.ok) { throw new Error("HTTP error, status = " + response.status); } return response.json(); }) .then(function(json) { for(var i = 0; i < json.current.length; i++) { var listItem = document.createElement('li'); listItem.innerHTML = '<strong>' + json.current.temp + '</strong>'; myList.appendChild(listItem); } }) .catch(function(error) { var p = document.createElement('p'); p.appendChild( document.createTextNode('Error: ' + error.message) ); document.body.insertBefore(p, myList); });

Check Cart Amount and Applied Coupons…

/* Change shipping based on total cost purchased and or applied coupons are excluded. */ add_filter( 'woocommerce_shipping_packages', 'hide_flat_rate_if_cart_total_is_greater_than_threshold', 5, 1 ); function hide_flat_rate_if_cart_total_is_greater_than_threshold( $packages ) { $threshold1 = 249; $applied_coupons = WC()->session->get( 'applied_coupons', array() ); $amount = WC()->cart->cart_contents_total; $availableRates = $packages[0]['rates']; $excluded_coupons = array('coupon1', 'coupon2', 'coupon3', 'coupon4', 'coupon5', 'coupon6', 'cooupon7', 'eight', 'nine', 'ten'); $isExcludedCoupon = false; $map = array_map(function($c) use($excluded_coupons, &$isExcludedCoupon ){ if( in_array($c, $excluded_coupons) ){ $isExcludedCoupon = true; } return $c; }, $applied_coupons); $flatRateKey = ''; array_map(function($r) use($availableRates, &$flatRateKey){ $id = $r->get_id(); $pos = substr_count($id, 'flat_rate'); if($pos == 1 ){ $flatRateKey = $id; } return $r; }, $availableRates); if

skew css

.w-button { padding: 10px 0; transform: skewX(-18deg); } .skew-text { color: #000; display: inline-block; transform: skewX(18deg); }

ternary or shorthand

It's commonly referred to as 'shorthand' or the Ternary Operator. $test = isset($_GET['something']) ? $_GET['something'] : ''; means if(isset($_GET['something'])) { $test = $_GET['something']; } else { $test = ''; } To break it down: $test = ... // assign variable isset(...) // test ? ... // if test is true, do ... (equivalent to if) : ... // otherwise... (equivalent to else) Or... // test --v if(isset(...)) { // if test is true, do ... (equivalent to ?) $test = // assign variable } else { // otherwise... (equivalent to :)