search

Archives: Snippets | Page 10

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;
});

Add a New Country to WooCommerce Countries List

The following snippet is taken from WooCommerce documentation and does exactly what you think. Add this snippet to your functions.php file to add a new country to the WooCommerce countries list:

function woo_add_my_country( $country ) {
   $country["AE-DU"] = 'Dubai';
   return $country;
}
add_filter( 'woocommerce_countries', 'woo_add_my_country', 10, 1 );

Modify Title Tag on Paginated Pages

If you look at the source of paginated pages on your blog, you will see they all share the same title tag. To avoid duplicate <title> tags, add the page number to the end of the tag. You can do this (assuming you use WordPress SEO by Yoast) by adding the following code to your functions.php file:

function change_yoast_title($title) {
	$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
	if ( is_paged() ) {
		return $title . ' - Page ' . $paged;
	}
	else {
		return $title;
	}
}
add_filter('wpseo_title','change_yoast_title');

Remove Canonical URL from Search Results

If you want to remove canonical URLs from search results in WordPress, and you use WordPress SEO by Yoast, add the following filter to your child theme’s functions.php file:

function yoast_remove_canonical_search( $canonical ) {
	if( is_search() ) {
		return false;
	} else {
		return $canonical;
	}
}
add_filter('wpseo_canonical', 'yoast_remove_canonical_search');

More on what a canonical tag is and how to use it in the post What is a Canonical Tag and how to use it?

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.

Savvy WordPress Development official logo