search ]

Archives: Snippets | Page 9

Remove URL Field from WordPress Comment Form

WordPress comments come by default with a field named “Website” or “URL”. If you want to remove this field, whether for design or to remove a field that is usually unnecessary, use the following snippet in functions.php:

function savvy_disable_comment_url($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','savvy_disable_comment_url');

This uses a WordPress filter. Learn more in WordPress Hooks Explained.

Show Prices Only to Logged-In Users in WooCommerce

There are many situations where you want to hide prices in your WooCommerce store and show them only to certain users by some criterion. WooCommerce has a filter called woocommerce_get_price_html that makes this easy:

add_filter( 'woocommerce_get_price_html', function( $price ) {
	if ( is_user_logged_in() ) return $price;
	return '';
} );

In the code above (add to functions.php) we used a condition that if the user is not logged in, prices will not be shown in the store. You can of course use any condition you choose.

For more WooCommerce customization, see Mastering WooCommerce Hooks.

Enable Maintenance Mode in WordPress

Need a quick way to enter maintenance mode in WordPress? Use the following snippet. Simply comment it out when you want to disable maintenance mode…

function maintenace_mode() {

	if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
		die('Maintenance.');
	}
}
add_action('get_header', 'maintenace_mode');

Add a New User via functions.php

If you are stuck without database or phpMyAdmin access, and cannot reset a password via the WordPress admin, take a look at the following code.

Add it to your theme’s functions.php file, change the details on lines 2-4 (to ones that do not exist for any existing user), and the next time you access the WordPress login screen a new user with administrator permissions will be created and you can log in.

function sv_wp_admin_account(){
	$user = 'Username';
	$pass = 'Password';
	$email = 'email@domain.co.il';
	if ( !username_exists( $user )  && !email_exists( $email ) ) {
		$user_id = wp_create_user( $user, $pass, $email );
		$user = new WP_User( $user_id );
		$user->set_role( 'administrator' );
	} }
add_action('init','sv_wp_admin_account');

Check if a Gravatar Exists for a User

The following function checks whether a Gravatar exists for a given email or user ID in WordPress and returns a boolean. Add this code to your theme’s functions.php file:

/**
 * Utility function to check if a gravatar exists for a given email or id
 * @param int|string|object $id_or_email A user ID,  email address, or comment object
 * @return bool if the gravatar exists or not
 */

function validate_gravatar($id_or_email) {
	//id or email code borrowed from wp-includes/pluggable.php
	$email = '';
	if ( is_numeric($id_or_email) ) {
		$id = (int) $id_or_email;
		$user = get_userdata($id);
		if ( $user )
			$email = $user->user_email;
	} elseif ( is_object($id_or_email) ) {
		$allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
		if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
			return false;

		if ( !empty($id_or_email->user_id) ) {
			$id = (int) $id_or_email->user_id;
			$user = get_userdata($id);
			if ( $user)
				$email = $user->user_email;
		} elseif ( !empty($id_or_email->comment_author_email) ) {
			$email = $id_or_email->comment_author_email;
		}
	} else {
		$email = $id_or_email;
	}

	$hashkey = md5(strtolower(trim($email)));
	$uri = 'http://www.gravatar.com/avatar/' . $hashkey . '?d=404';

	$data = wp_cache_get($hashkey);
	if (false === $data) {
		$response = wp_remote_head($uri);
		if( is_wp_error($response) ) {
			$data = 'not200';
		} else {
			$data = $response['response']['code'];
		}
		wp_cache_set($hashkey, $data, $group = 'has_gravatar', $expire = 60*5);

	}
	if ($data == '200'){
		return true;
	} else {
		return false;
	}
}

Use the function like this:

$author_id = get_the_author_meta( 'ID' );

if (validate_gravatar($author_id)) {...}
	

For more WordPress tips, see What is WordPress?.

Send Email on New Post Published in WordPress

Here is a short snippet that sends an email when you publish a new post on your blog. This code can also work for Custom Post Types.

add_action('future_to_publish', 'send_emails_on_new_event');
add_action('new_to_publish', 'send_emails_on_new_event');
add_action('draft_to_publish' ,'send_emails_on_new_event');
add_action('auto-draft_to_publish' ,'send_emails_on_new_event');
 
/**
 * Send emails on event publication
 *
 * @param WP_Post $post
 */
function send_emails_on_new_event($post)
{
    $emails = "email_1@mail.com, email_2@mail.com"; //If you want to send to site administrator, use $emails = get_option('admin_email');
    $title = wp_strip_all_tags(get_the_title($post->ID));
    $url = get_permalink($post->ID);
    $message = "Link to post: n{$url}";
 
    wp_mail($emails, "New post published: {$title}", $message);
}

The result will look something like:

[Title] New post published: Your Post
    
Link to post:
http://site.co.il/your-post/

If you want to enable this for a specific Custom Post Type, add a condition inside the function like this:

...
if(get_post_type($post->ID) === 'page') //post, page, attachment or whatever other CPT you may have
{
    //use wp_mail() here!
}
...

Add User Role to Body Class in WordPress Admin

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.

Reorder the Admin Menu in WordPress

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.

Add CSS to ACF WYSIWYG Editor

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;
});
Savvy WordPress Development official logo