Here is a way to add a class based on the user role in the WordPress admin. Add the following code to your theme’s functions.php file:
add_filter('admin_body_class', function($classes) {
global $current_user;
if(is_array($current_user->roles)) {
foreach($current_user->roles as $role) {
$classes .= "user-role-{$role} ";
}
}
return rtrim($classes);
});
The result will look something like:
<body class="... user-role-administrator ...">
This uses the body_class filter. Learn more in WordPress Hooks Explained.
A short snippet that lets you change the order of the menu in the WordPress dashboard. Simply choose the order you want in the $reordered_items array. You can use var_dump($menu_order) to find all menu items.
Items will appear under the top-level item (Dashboard).
add_filter('menu_order', 'reorder_admin_menu', 999);
/**
* Reorders admin menu to match the wanted order
*
* @param $menu_order
* @return mixed
*/
function reorder_admin_menu($menu_order) {
$reordered_items = array(
'edit.php?post_type=page',
'edit.php'
);
$reordered_items_insertion_point = 'index.php';
$filtered_menu_order = array_diff($menu_order, $reordered_items);
$new_menu_order = array();
foreach($filtered_menu_order as $menu_item) {
$new_menu_order[] = $menu_item;
if($menu_item === $reordered_items_insertion_point) {
$new_menu_order = array_merge($new_menu_order, $reordered_items);
}
}
return $new_menu_order;
}
This uses a WordPress filter. Learn more in WordPress Hooks Explained.
Example of adding a CSS file from your theme to the WYSIWYG editor of the Advanced Custom Fields plugin. The code below also works on the frontend if you use the acf_form() function.
add_filter( 'tiny_mce_before_init', function($mce_init) {
$content_css = get_stylesheet_directory_uri() . '/your-custom-css.css';
if (isset($mce_init[ 'content_css' ])) {
$mce_init[ 'content_css' ] = "{$mce_init['content_css']},{$content_css}";
}
return $mce_init;
});
The following code lets you add a product to the cart automatically:
/**
* Automatically add product to cart on visit
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 64; //replace with your own product id
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
If you want to add a product automatically based on cart total, use this code:
/**
* Add another product depending on the cart total
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 2831; //replace with your product id
$found = false;
$cart_total = 30; //replace with your cart total needed to add above item
if( $woocommerce->cart->total >= $cart_total ) {
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
$woocommerce->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
Take a look at the post How to add products to cart via link.
The following snippet lets you send an email with the coupon details used in a specific order. You can change the recipient and the message as desired. The code runs when the user who placed the order reaches the WooCommerce Thank You page.
/**
* Send an email each time an order with coupon(s) is completed
* The email contains coupon(s) used during checkout process
*
*/
function woo_email_order_coupons( $order_id ) {
$order = new WC_Order( $order_id );
if( $order->get_used_coupons() ) {
$to = 'youremail@yourcompany.com';
$subject = 'New Order Completed';
$headers = 'From: My Name <youremail@yourcompany.com>' . "rn";
$message = 'A new order has been completed.n';
$message .= 'Order ID: '.$order_id.'n';
$message .= 'Coupons used:n';
foreach( $order->get_used_coupons() as $coupon) {
$message .= $coupon.'n';
}
@wp_mail( $to, $subject, $message, $headers );
}
}
add_action( 'woocommerce_thankyou', 'woo_email_order_coupons' );
A short snippet I use often when I need to scroll to a specific element (by ID). Simply change ‘600’ to the speed you want the scroll to run (ms). You can also change the selector a[href*="#"] to whatever selector you choose.
$('a[href*="#"]').on('click', function (e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top
}, 600, 'linear');
});
Nice, right? Check out the demo I created on Codepen. If you run into smooth scrolling issues or frontend scrolling performance problems, take a look at the link above.
Here is also a post on how to create on-scroll animations using the AOS library.
There are situations where you want to limit content editors from uploading images beyond a certain size. You can even be more specific and allow uploads of a specific pixel size. Add the following code to your functions.php file:
/*
* Check image resolution (px) before crunching
*/
function savvy_validate_image_size( $file ) {
$image = getimagesize($file['tmp_name']);
$minimum = array(
'width' => '460',
'height' => '460'
);
$maximum = array(
'width' => '1280',
'height' => '1280'
);
$image_width = $image[0];
$image_height = $image[1];
$too_small = "Image dimensions are too small. Minimum size is {$minimum['width']} by {$minimum['height']} pixels. Uploaded image is $image_width by $image_height pixels.";
$too_large = "Image dimensions are too large. Maximum size is {$maximum['width']} by {$maximum['height']} pixels. Uploaded image is $image_width by $image_height pixels.";
if ( $image_width < $minimum['width'] || $image_height < $minimum['height'] ) {
$file['error'] = $too_small;
return $file;
}
elseif ( $image_width > $maximum['width'] || $image_height > $maximum['height'] ) {
$file['error'] = $too_large;
return $file;
}
else
return $file;
}
add_filter('wp_handle_upload_prefilter','savvy_validate_image_size');
You can change the minimum and maximum width and height (pixels) on lines 6-12. Take a look at the broader post on image sizes in WordPress.
WooCommerce has a built-in option to redirect all users to the cart page when they add a product. This option is under WooCommerce > Settings > Products > “Add to cart behaviour”.
But if you want to redirect visitors directly to the checkout page, add the following code to your active child theme (or theme) functions.php file:
function custom_add_to_cart_redirect( $url ) {
$url = WC()->cart->get_checkout_url();
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );
This code redirects users directly to the checkout page after adding a product to the WooCommerce cart. On the same topic, see the post Popup after adding to cart in WooCommerce.
For more on adding fields and modifying the WooCommerce checkout page, see WooCommerce checkout – how to change and add fields.
The following snippet lets you limit WordPress search to a specific Custom Post Type so results come only from that post type. Add to functions.php and set the post type(s) to search on line 4:
function SearchFilter($query) {
if ($query->is_search) {
// Insert the specific post type you want to search
$query->set('post_type', 'feeds');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
By default, WordPress does not allow all types of code in the WordPress content editor. For example, Inline SVGs contain many tags such as <def>, <rect>, etc. To allow Inline SVG, use the following code in functions.php:
function override_mce_options($initArray) {
$opts = '*[*]';
$initArray['valid_elements'] = $opts;
$initArray['extended_valid_elements'] = $opts;
return $initArray;
}
add_filter('tiny_mce_before_init', 'override_mce_options');
Note that this code allows any tag, whether SVG-related or not.