This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

wp cli workflow and installation script

Here’s a small shell script that I use to install WordPress locally, you will need to install wp-cli

Once you have wp-cli install simply save this script in to a file named ‘install.sh’ and ensure it lives in the folder you want to install WordPress then from the command line ‘cd’ into the folder where it lives and run ‘sh install.sh’ and follow the prompts in your terminal.

#!/bin/sh
# download the core
wp core download --locale=en_GB

# setup the wp-config
read -p "DB Name?: " -e DBNAME
read -p "DB Prefix?: " -e DBPREFIX

# to create the wp-config file with parameters set above
# Note the dbuser and dbpass are set here for a local development setup
wp config create --dbname=$DBNAME --dbuser=root --dbpass="" --dbprefix=$DBPREFIX --extra-php <<PHP
define( 'WP_DEBUG', true );
define( 'DISALLOW_FILE_EDIT', true);
PHP
# --extra-php is just some standard stuff I like to set up with every install

# creates the db using the parameters set above
wp db create

read -p "URL?: " -e URL
read -p "Title?: " -e TITLE
read -p "Admin email?: " -e ADEMAIL
read -p "Admin username?: " -e ADUSERNAME
read -p "Admin password?: " -e ADPASSWORD

# installs WordPress using the parameters set above
wp core install --url=$URL --title="$TITLE" --admin_email=$ADEMAIL --admin_user=$ADUSERNAME --admin_password=$ADPASSWORD

# this is just something else I like to setup with every install, saves me having to manually set it
# here you can add other options you find yourself setting everytime you install WordPress
wp option update permalink_structure '/%postname%/'

This might not run on your local machine but it works in my Mac OS environment and you may need to adapt it to work on your setup.

Create a specific menu for logged in users

Here’s a way to add a specific menu for logged in users, this is useful if you’re building a membership site, where users need to login first but no longer need to see the login link after login and the menu can then be replaced with a users Account, Settings or Preferences menu.

So, first of all, we will need 2 menu locations.

One for logged out users to login, and one for users after they have logged in.

// Register Navigation Menus
function wpstx_logged_in_user_menu() {

	$locations = array(
		'logged-in-menu' => __( 'User Menu', 'wpstx_logged_in_user_menu' ),
		'logged-out-menu' => __( 'Login', 'wpstx_logged_in_user_menu' ),
	);
	register_nav_menus( $locations );

}
add_action( 'init', 'wpstx_logged_in_user_menu' );

Next, we need to create an action hook that renders the menu conditionally depending if the user is logged in or not. Here we will use PHP Ternary operator logic on the built-in WordPress function is_user_logged_in() to render the one menu or the other.

// Function with a conditional for logged in/out users
function wpstx_users_menu() {
    wp_nav_menu(
        array(
            'theme_location' => is_user_logged_in() ? 'logged-in-menu' : 'logged-out-menu'
        )
    );
}
// create an action hook for uses in your theme
// to render the menu simply add "do_action('wpstx_users_menu');" anywhere in your theme
add_action('wpstx_users_menu','wpstx_users_menu');

This action hook can then be used in your theme’s header/footer or wherever you want to put it to conditionally render the function...

// add this to one of your template files
do_action('wpstx_users_menu');

With this snippet running all you need to do now is go to:
Dashboard > Appearance > Menus
to create a couple of menus and allocate them to the relevant menu locations.

Create a menu for non-logged in users
Create a menu for logged in users
How the menu looks to users who are not logged in
How the menu looks to users who are logged in

@source https://github.com/eirichmond/wpstx-specific-menu-for-loggedin-users

Add custom meta column in the Users list

This is a very simple way to add a custom column to display in your user’s list. Say you want to show some preference that’s been added to the user’s profile with add_user_meta

First of all, let’s register the extra column

/**
 * The function hooked to the filter hook manage_users_columns that simply
 * adds a new column by key and value to the existing core columns for the users list
 * 
 * @author  Elliott Richmond <me@elliottrichmond.co.uk>
 * @since 0.1.0
 * @param array   $columns    Existing columns array.
 * @return string $columns    The new columns array.
 * 
 */
function wpstx_custom_user_columns($columns) {
    $columns['select_role'] = 'Preference';
    return $columns;
}
add_filter('manage_users_columns', 'wpstx_custom_user_columns', 10, 1);

Next, we’ll add the data that you want to show when that row is rendered, if the column name is equal to the key we provided above in the manage_users_colums hook we’ll use get_user_meta to get the data we want to show by the users ID and return the value.

/**
 * The function hooked to the filter hook manage_users_custom_column that displays
 * the information we want to see by the in individual user by ID or row listed
 * 
 * @author  Elliott Richmond <me@elliottrichmond.co.uk>
 * @since 0.1.0
 * @param string   $val    		   Existing columns array.
 * @param string   $column_name    The key value of the column that we will switch to set in our function 'wpstx_custom_user_columns'.
 * @param int      $user_id    	   The users ID used to identify the row the list is going to output.
 * 
 * @return string  $val    		   The existing or new string we want to display in the users list.
 * 
 */
function wpstx_custom_user_row( $val, $column_name, $user_id ) {
    switch ($column_name) {
		case 'select_role' :
			$meta_key = get_user_meta($user_id, 'select_role', true);
			$val = wpstx_select_role_output($meta_key);
			return $val;
        default:
    }
    return $val;
}
add_filter( 'manage_users_custom_column', 'wpstx_custom_user_row', 10, 3 );

You’ll notice I’m also using a function on the meta value, this is just a simple helper function to change the output by the key saved in the user’s meta, rather than use my function you could simply return $meta_key instead.

/**
 * This is an extra function to change a lowercase meta key
 * from the standard WordPress way of storing keys and changing
 * them to our prefered value as defined by the key value
 * 
 * @author  Elliott Richmond <me@elliottrichmond.co.uk>
 * @since 0.1.0
 * @param string  $meta_key    The incoming meta key.
 * @return string $preference  The output text.
 * 
 */
function wpstx_select_role_output($meta_key) {
	// die early if empty
	if ($meta_key == '') {
		return;
	}
	$output = array(
		'subscriber' => 'Recieve snippets',
		'contributor' => 'Submit snippets',
	);
	$preference = $output[$meta_key];
	return $preference;
}

@source https://github.com/eirichmond/wpstx-user-columns.git

Use a custom post type to send notifications as Html emails to users by the user role

When I set WP Snippets til Christmas up this year I wanted to send an email to all the previous contributors just to notify them this was going to be a thing again for 2019.

As the previous contributors were already registered users and rather than subscribe to a third-party service I wanted to see how I could do this with WordPress core, can’t be that difficult right? So with a little bit of thought and rough testing, I started to formulate a plan.

I needed to think about all the pitfalls and what I wanted to do. First of all, I needed a custom post type but, how was I going to trigger the send? I couldn’t do it on the save_post action hook otherwise the post would get emailed every time it was updated. I would also need to be careful about sending on the save_post with multiple users too, waiting for a post to save after trying to send 300 users an email could take forever! How could I stagger the sending to avoid getting blocked or banned by the server? Would I need to set some post meta on the post as a ‘sent email notification’ marker just so I didn’t send it again? Perhaps I could use the WP Cron to schedule an event to check all Published posts that hadn’t been already been sent by email…

…so with all this in mind, I ended up doing it like so, first all I needed a custom post type but take it out of public visibility.

/**
 * Register a custom post type to handle all the emails notifications.
 * The labels and arguments here might be overkill but I used https://generatewp.com/post-type/
 * to generate the code so you get what is generated.
 * 
 * @source GenerateWP https://generatewp.com/post-type/
 * 
 */
function email_notification() {

	$labels = array(
		'name'                  => _x( 'Emails', 'Post Type General Name', 'wpstx-email-notification-with-post-type' ),
		'singular_name'         => _x( 'Email', 'Post Type Singular Name', 'wpstx-email-notification-with-post-type' ),
		'menu_name'             => __( 'Email Users', 'wpstx-email-notification-with-post-type' ),
		'name_admin_bar'        => __( 'Email', 'wpstx-email-notification-with-post-type' ),
		'archives'              => __( 'Item Archives', 'wpstx-email-notification-with-post-type' ),
		'attributes'            => __( 'Item Attributes', 'wpstx-email-notification-with-post-type' ),
		'parent_item_colon'     => __( 'Parent Item:', 'wpstx-email-notification-with-post-type' ),
		'all_items'             => __( 'All Items', 'wpstx-email-notification-with-post-type' ),
		'add_new_item'          => __( 'Add New Item', 'wpstx-email-notification-with-post-type' ),
		'add_new'               => __( 'Add New', 'wpstx-email-notification-with-post-type' ),
		'new_item'              => __( 'New Item', 'wpstx-email-notification-with-post-type' ),
		'edit_item'             => __( 'Edit Item', 'wpstx-email-notification-with-post-type' ),
		'update_item'           => __( 'Update Item', 'wpstx-email-notification-with-post-type' ),
		'view_item'             => __( 'View Item', 'wpstx-email-notification-with-post-type' ),
		'view_items'            => __( 'View Items', 'wpstx-email-notification-with-post-type' ),
		'search_items'          => __( 'Search Item', 'wpstx-email-notification-with-post-type' ),
		'not_found'             => __( 'Not found', 'wpstx-email-notification-with-post-type' ),
		'not_found_in_trash'    => __( 'Not found in Trash', 'wpstx-email-notification-with-post-type' ),
		'featured_image'        => __( 'Featured Image', 'wpstx-email-notification-with-post-type' ),
		'set_featured_image'    => __( 'Set featured image', 'wpstx-email-notification-with-post-type' ),
		'remove_featured_image' => __( 'Remove featured image', 'wpstx-email-notification-with-post-type' ),
		'use_featured_image'    => __( 'Use as featured image', 'wpstx-email-notification-with-post-type' ),
		'insert_into_item'      => __( 'Insert into item', 'wpstx-email-notification-with-post-type' ),
		'uploaded_to_this_item' => __( 'Uploaded to this item', 'wpstx-email-notification-with-post-type' ),
		'items_list'            => __( 'Items list', 'wpstx-email-notification-with-post-type' ),
		'items_list_navigation' => __( 'Items list navigation', 'wpstx-email-notification-with-post-type' ),
		'filter_items_list'     => __( 'Filter items list', 'wpstx-email-notification-with-post-type' ),
	);
	$args = array(
		'label'                 => __( 'Email', 'wpstx-email-notification-with-post-type' ),
		'description'           => __( 'Email notification system', 'wpstx-email-notification-with-post-type' ),
		'labels'                => $labels,
		'supports'              => array( 'title', 'editor' ),
		'hierarchical'          => false,
		'public'                => false,
		'show_ui'               => true,
		'show_in_menu'          => true,
		'menu_position'         => 25,
		'menu_icon'             => 'dashicons-email',
		'show_in_admin_bar'     => true,
		'show_in_nav_menus'     => false,
		'can_export'            => false,
		'has_archive'           => false,
		'exclude_from_search'   => true,
		'publicly_queryable'    => false,
		'capability_type'       => 'email_notification', // our own cap type
		'map_meta_cap'        	=> true,
		'capability'			=> array(
			'publish_posts'     => 'manage_email_notifications', // the capability to add to the role
		)
	);
	register_post_type( 'email_notification', $args );

}
add_action( 'init', 'email_notification' );

Add the capabilities to the Administrator so only admin can use this functionality, other roles can be added but to keep things simple we are only interested in Administrators for now.

/**
 * Add the capabilities to use this email system to the administrator only
 */
function wpstx_add_role_caps() {

	// The roles to manage this custom post type, other roles can been added to this array but we are only allowing this for Administrators
	$roles = array('administrator');
	
	// Loop through each role as it's an array and assign capabilities
	foreach($roles as $the_role) { 
		$role = get_role($the_role);
		$role->add_cap( 'read' );
		$role->add_cap( 'manage_email_notifications' );
		$role->add_cap( 'read_email_notification');
		$role->add_cap( 'read_private_email_notifications' );
		$role->add_cap( 'edit_email_notification' );
		$role->add_cap( 'edit_email_notifications' );
		$role->add_cap( 'edit_others_email_notifications' );
		$role->add_cap( 'edit_published_email_notifications' );
		$role->add_cap( 'publish_email_notifications' );
		$role->add_cap( 'delete_others_email_notifications' );
		$role->add_cap( 'delete_private_email_notifications' );
		$role->add_cap( 'delete_published_email_notifications' );

	}
}
add_action('admin_init','wpstx_add_role_caps');

Just for some additional and obvious user feedback, I wanted to change the “Publish” button to “Send” so here’s a very simple, fairly seasoned filter hook to do just that and only on my custom post type

/**
 * Change the button that says "Publish" to "Send" on the post type
 * "email_notifications" to make the UI look more obvious that the
 * user is about to send something.
 * 
 * @source https://developer.wordpress.org/reference/hooks/gettext/
 * 
 * @param 	string 	$translation 	Translated text
 * @param 	string 	$text 	Text to translate
 * @param 	string 	$domain 	Textdomain
 * @return 	string 	$translation 	Translated text
 * 
 */
function wpstx_change_publish_to_send( $translation, $text, $domain ) {
	if ( 'email_notification' == get_post_type() && ($text == 'Publish') ) {
		$translation = 'Send';
	}
	return $translation;
}
add_filter( 'gettext', 'wpstx_change_publish_to_send', 10, 3 );

I then needed to somehow save some post meta to the post that I could use later to find only published posts that hadn’t previously been sent, this can be done on the post_status auto-draft which is initiated as soon as a new post is created, I’ve also added a few other checks to stop the running of the function if its not needed.

/**
 * Save some post meta with the email_notification post type
 * on auto-draft or when the post if first initiated
 * 
 * @source https://developer.wordpress.org/reference/hooks/save_post/
 * 
 * @param 	int 		$post_id 	Auto generated post ID
 * @param 	object 		$post 		WP post object
 * @param 	boolean 	$update 	Whether this is an existing post being updated or not
 */
function wpstx_save_notification_status( $post_id, $post, $update = false ) {

	if ( ! current_user_can( 'edit_post', $post_id ) || $update) {
        return; // stop if the current user does not have capabilities to edit this or post is an update 
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return; // stop if the current post is auto saving
    }
	if( $post->post_type === 'email_notification' || $post->post_status === 'auto-draft' ) {
		add_post_meta($post_id, 'notification_sent', '0'); // add post meta that we will use in the wp cron later
	}

}
add_action( 'save_post', 'wpstx_save_notification_status', 10, 3 );

I also wanted to set the role for the email so that I could effectively segment different emails to different roles, for this I needed to add a custom meta box. This would require a function to add the meta box, a callback function renders the meta box and another function to save the post meta for that meta box, here’s all the code for just for that.

/**
 * Register some custom meta to select user role to email to.
 * 
 * @source https://developer.wordpress.org/reference/hooks/add_meta_boxes/
 */
function wpstx_register_meta_boxes() {
    add_meta_box( 'user-role', __( 'Role to Email', 'wpstx-email-notification-with-post-type' ), 'wpstx_my_display_callback', 'email_notification' );
}
add_action( 'add_meta_boxes', 'wpstx_register_meta_boxes' );

/**
 * Render the meta box to display in the backend.
 * We are also getting all the current WordPress roles with the global $wp_roles
 * here so we can isolate what role to set the email notification to send to
 *
 * @param	object	$post	Current post object.
 */
function wpstx_my_display_callback( $post ) {
	global $wp_roles;
	$roles = $wp_roles->roles;

	// for security when saving the data later
	wp_nonce_field( 'role_to_email', 'role_to_email_nonce' ); 
	// get the current value to check against
	$role_to_email = get_post_meta( $post->ID, '_role_to_email', true ); 

	?>
	<!-- set a label with translation just because it's good practice -->
	<label for='role_to_email'>
		<?php _e( 'Select the user role to email', 'wpstx-email-notification-with-post-type' ); ?>
	</label>
	<!-- add the name key '_role_to_email' for indexing the meta -->
	<select name='_role_to_email'>
		<!-- set a default of selected but disabled on render if the an option hasn't already been selected -->
		<option value='' selected disabled>Select Role</option>
		<?php foreach($roles as $k => $role) { ?>
			<!-- the currently selected option using the wp core function "selected" https://developer.wordpress.org/reference/functions/selected/ -->
			<option value='<?php echo esc_attr($k); ?>' <?php selected( $role_to_email, $k, true ); ?>><?php echo esc_attr($role['name']); ?></option>
		<?php } ?>

	</select>

	<?php
}


/**
 * Save meta box content.
 *
 * @param 	int 	$post_id 	Post ID
 * 
 * @source https://developer.wordpress.org/reference/hooks/save_post/
 */
function wpstx_save_meta_box( $post_id ) {
	if ( ! isset( $_POST['role_to_email_nonce'] ) ) {
        return; // stop if the nounce is not set
    }
    if ( ! wp_verify_nonce( $_POST['role_to_email_nonce'], 'role_to_email' ) ) {
        return; // stop if the nounce doesn't varify
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return; // stop if auto saving the post
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return; // stop if the current user does not have capabilities to edit this or post
    }
    if ( isset( $_POST['post_type'] ) && 'email_notification' === $_POST['post_type'] ) {
		// only happens if the post type is "email_notification" 
		if(isset($_POST['_role_to_email'])) {
			// only happens if name key is set
			update_post_meta($post_id, '_role_to_email', esc_attr($_POST['_role_to_email']));
		}
    }
}
add_action( 'save_post', 'wpstx_save_meta_box', 10, 1 );

In the above code, a role is set so, I needed a helper function to get all the users for a particular role that will be needed during the sending of the email later in a WP Cron event, this function returns all the users from a particular role if the role is set.

/**
 * A simple helper function to get all users by role if the parameter is set
 * 
 * @param	string/array	$roles	Key for role set in WordPress roles
 */
function wpstx_get_users($roles = '') {
    $args = array();
    if($roles) {
        $args['role'] = $roles;
    }
    $users = get_users($args);
    return $users;
}

So next up comes the WP Cron event itself which is a fair chunk of code. I’ve heavily commented on it line by line to describe what is going on.

It describes what happens after an email notification is set to “Publish” or when “Send” is clicked in the UI for the email notification.

The next custom WP Cron event will get all published posts that do not have a custom meta “notification_sent” equal to “1” then look for all users of a particular role, then set up the email from the post content as a HTML email, send the email, wait 10 seconds and continue to the next user to send another email.

/**
 * This function takes care of all the sending of emails that
 * are hooked to our custom action hook scheduled by the wp cron
 */
function wpstx_send_emails() {

	// get all the posts that are set to published and that
	// do not have a meta key 'notification_sent' set to '1'
	// we will set this to '1' after the email notification is sent
	// this will ensure that we don't send it again
	// https://developer.wordpress.org/reference/functions/get_posts/
	$emails = get_posts(
		array(
			'post_type' => 'email_notification',
			'post_status' => 'publish',
			'meta_key' => 'notification_sent',
			'meta_value' => '1',
			'meta_compare' => '!='
		)
	);

	// $emails will return and array of objects so we'll use a
	// foreach to loop the email notifications ready to send
	foreach ($emails as $send_email) {

		// get role set for sending the email notification 
		$role = get_post_meta($send_email->ID, '_role_to_email', true);
		// if $role is set pass it to helper function 'wpstx_get_users()'
		if(isset($role) && $role != '') {
			$users = wpstx_get_users($role);
		} else {
			$users = wpstx_get_users();
		}

		// now we have all the users to send an email notification to
		// and we can use the $send_email post object to setup some parameters
		foreach ($users as $user) {

			// get the post title by ID and set the subject line for the email
			// https://developer.wordpress.org/reference/functions/get_the_title/
			$subject = get_the_title( $send_email->ID );
			// we only need the post_content of the post and we will filter it using the_content
			// https://developer.wordpress.org/reference/functions/get_post_field/
			// https://developer.wordpress.org/reference/hooks/the_content/
			$content = apply_filters('the_content', get_post_field('post_content', $send_email->ID));
			// load the $message variable with a personalised "Hey username" 
			$message = '<p>Hey ' . $user->user_login . '</p>';
			// concatinate the $content to the end of the "Hey..." $message variable
			$message .= $content;
			// as we are sending html we need to set an email header as an array
			$headers = array('Content-Type: text/html; charset=UTF-8');
			// Send the email to the user with the subject, message and headers.
			// https://developer.wordpress.org/reference/functions/wp_mail/
			wp_mail($user->user_email, $subject, $message, $headers);
			// IMPORTANT!!
			// Your host will have a limit on the amount of eamils you can send per minute/hour from your
			// server so it is super important to set a delay between each emails sent, otherwise
			// you could get your hosting account temporarily blocked on banded for spammy looking activity.
			// I'm simpy using a 10 second delay between each sending of an email, you might need to increase
			// this depending on the amount of users you have to send to
			sleep(10);

		}

		// Once the email has been sent now set the post with a post meta
		// key 'notification_sent' equal to '1' this will ensure we never
		// pick it up as published post to send again as set in the
		// WordPress function get_posts() above.
		update_post_meta($send_email->ID, 'notification_sent', '1');

	}

}
add_action( 'wpstx_check_scheduled_emails', 'wpstx_send_emails' );

/**
 * This sets the next event time for our action hook
 * "wpstx_check_scheduled_emails" that fires "wpstx_send_emails"
 */
wp_next_scheduled( 'wpstx_check_scheduled_emails' );

/**
 * This checks if the event is set or past and sets a new one if it has past
 * or at least that's the way I interpret the way it works :)
 */
if ( ! wp_next_scheduled( 'wpstx_check_scheduled_emails' ) ) {
	// now we can tap in to the WordPress cron schedule, there is a choice of
	// ‘hourly’, ‘twicedaily’, and ‘daily’
	// you can set your own custom time intervals as well 
	// https://developer.wordpress.org/plugins/cron/understanding-wp-cron-scheduling/
	// in this case we are firing the custom action hook "wpstx_check_scheduled_emails"
	// on the next hourly interval
    wp_schedule_event( time(), 'hourly', 'wpstx_check_scheduled_emails' );
}

The benefit of doing it this way free’s up the backend processing time and user’s interaction by pushing all the heavy work to a background cron event, you don’t have to click a button and wait for the process to finish which could be a while, for instance, if you had 1000 users with a 10 second delay between sending each email 🙂

And here is a final job to remove the schedule, this is just good practice if it is a plugin for instance and you wanted to remove the event after deactivation of the plugin.

/**
 * Setup a deactivation hook to remove this cron if this plugin is disabled
 * 
 * @source https://developer.wordpress.org/reference/functions/register_deactivation_hook/
 */
function wpstx_deactivate_email_notification_cron() {
	// retrieve the event
	$timestamp = wp_next_scheduled( 'wpstx_check_scheduled_emails' );
	// unset the event
	wp_unschedule_event( $timestamp, 'wpstx_check_scheduled_emails' );
}
register_deactivation_hook( __FILE__, 'wpstx_deactivate_email_notification_cron' );

That’s how I set up a custom post type as an Email Notification system using the WP Cron.

@github https://github.com/eirichmond/wpstx-email-notification-with-post-type

Action hook after opening body tag

Before WordPress 5.2.0 it was always a hassle to add anything just after the opening HTML body tag in your theme. For the release of 5.2.0 came the action hook “wp_body_open”. This was added to core and of course, your theme or any themes for this release need to be compatible with core but we’ll come to that bit later, first let’s look at what can be done with the action hook.

// Add your code after opening body tag.
add_action( 'wp_body_open', 'wpstx_add_after_opening_body_tag' );
function wpstx_add_after_opening_body_tag() {
    echo '<!-- added your code here en -->';
}

For backward compatibility you should add this to your theme immediately after your opening body tag. If you are using a premium theme ask the theme developer to add this if it doesn’t already exist

<?php
if ( function_exists( 'wp_body_open' ) ) {
    wp_body_open();
}
?>

@source https://developer.wordpress.org/reference/functions/wp_body_open/

Notify WordPress users of newly published custom post types

So it’s Christmas Eve and this is the final snippet for this year, it’s been fun and even better than last years! I’d like to thank each and everyone of the submitters and the subscribers without which this would really be nothing so, thank you all so much and Merry Christmas now on with the snippets 🙂

Say you have a custom post type and each time you publish a new custom post you’d like to notify all your users. It could be a product, an event, a tutorial or perhaps a lesson etc.

Usually the action hook would be ‘publish_post’ or ‘publish_page’ but those hooks only work for Posts and Pages, these hooks will not work with custom post types! So, what about custom post types?

The following example shows how this can be done to notify users that a Deputy Head has submitted a lesson for review:

function notify_teachers($post_ID)  {
	// a conditional to check that this is a new post
	if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) {
		// get all users email addresses
		$wp_user_search = new WP_User_Query( array( 'fields' => array('user_email') ) );
		$usersarray = $wp_user_search->get_results();
		$arrUsers = array();
		// store each email for later use
		for ($arr = $usersarray, $mU = count($arr), $iU = 0; $iU < $mU; $iU++) {
			$arrUsers[] = $arr[$iU]->user_email;
		}
		// create the from details 
		$headers[] = 'From: Deputy Head <dephead@example.net>';
		// lets cc in the head just because we can 
		$headers[] = 'Cc: The Head <thehead@example.net>';
		// separate the users array
		$users = implode(",", $arrUsers);
		// concatenate a message together
		$message = 'A new lesson has been opened for your review on the site ' . get_bloginfo('siteurl') . "\r\n\r\n";
		$message .= 'You can review it now at ' . get_permalink($post_ID) . "\r\n\r\n";
		$message .= 'Feel free to leave a comment and any suggestions.' . "\r\n\r\n";
		$message .= 'Deputy Head.';
		// and finally send the email
		wp_mail($users, "Lesson Notice: "  . $_POST['post_title'] , $message, $headers );
	    return $post_ID;
    }
}
// hook on to the custom post type by using 'publish_lesson'
add_action('publish_lesson', 'notify_teachers');

Out of the box the action hook would usually be ‘publish_post’ but if you have registered a custom post type called ‘lesson’ you can now use ‘publish_lesson’ to hook your function, it really is as simple as that.

Create a welcome email for newly added WordPress users

This is a welcome email plugin that needs to go into your plugins folder, create a file called something like welcome.php or welcome-email.php and paste the following code in to that file. The file then needs to be copied to your wp-content/plugins/ folder. Once uploaded login to your dashboard > plugins and look for the newly added plugin then activated it.

Now you will have more of a personalised message for your newly registered users. Changes can be made in the plugin to adapt the message you would like triggered.

<?php
/*
Plugin Name: Welcome Email
Plugin URI: http://www.squareonemd.co.uk/
Description: This plugin allows Administrators to change the standard WordPress welcome email.
Author: Elliott Richmond
Version: 1.0
Author URI: http://www.squareonemd.co.uk/
*/

// Redefine user notification function
if ( !function_exists('wp_new_user_notification') ) {

	function wp_new_user_notification( $user_id, $plaintext_pass = '' ) {

		$user = new WP_User( $user_id );

		$user_login = stripslashes( $user->user_login );
		$user_email = stripslashes( $user->user_email );

		$message  = sprintf( __('New user registration on %s:'), get_option('blogname') ) . "\r\n\r\n";
		$message .= sprintf( __('Username: %s'), $user_login ) . "\r\n\r\n";
		$message .= sprintf( __('E-mail: %s'), $user_email ) . "\r\n";

		@wp_mail(
			get_option('admin_email'),
			sprintf(__('[%s] New User Registration'), get_option('blogname') ),
			$message
		);

		if ( empty( $plaintext_pass ) )
			return;

		$message  = __('Hi there ') . $user_login . "\r\n\r\n";
		$message .= sprintf( __("Welcome to %s! Here's how to log in and download your items:"), get_option('blogname')) . "\r\n\r\n";
		$message .= site_url('/wp-admin/') . "\r\n";
		$message .= sprintf( __('Username: %s'), $user_login ) . "\r\n";
		$message .= sprintf( __('Password: %s'), $plaintext_pass ) . "\r\n\r\n";
		// define your email addres in this line
		$message .= sprintf( __('If you have any problems, please contact us at %s.'), 'admin@youremaildomain.co.uk' ) . "\r\n\r\n";
		$message .= __('Adios!');

		wp_mail(
			$user_email,
			sprintf( __('[%s] Your username and password'), get_option('blogname') ),
			$message
		);
	}
}

function sqpress_mail_from ($content_type) {
  // define the email address you want as the from field
  return 'admin@youremaildomain.co.uk';
}
add_filter('wp_mail_from','sqpress_mail_from');

function sqpress_mail_from_name($name) {
  // name of the account you want the email to appear in the client from field
  return 'SquarePress';
}
add_filter('wp_mail_from_name','sqpress_mail_from_name');

A useful way to create new WordPress arrays

Let say you have a set of data stored in an array and you want to isolate or create a new array with certain data.

There is a powerful function called wp_list_pluck() and wp_list_filter() that can be used for such tasks with any sort of datasets.

For example consider the following array:


$vehicles = array(
    array(
        'id' => 1,
        'type' => 'car',
        'color' => 'red',
    ),
    array(
        'id' => 2,
        'type' => 'car',
        'color' => 'blue',
    ),
    array(
        'id' => 3,
        'type' => 'car',
        'color' => 'red',
    ),
    array(
        'id' => 4,
        'type' => 'truck',
        'color' => 'green',
    ),
    array(
        'id' => 5,
        'type' => 'bike',
        'color' => 'blue',
    ),
);

First of all we can use wp_list_pluck() with 2 parameters, the array to pluck and the key to be plucked. So to create another array that contains just the key for the “type” we would do the following:

$new_array = wp_list_pluck($vehicles, 'type');
// would produce the following
// array('car', 'car', 'car', 'truck', 'bike');

The same could be done to collate the id’s for later loops:

$new_array = wp_list_pluck($vehicles, 'id');
// would produce the following
// array('1', '2', '3', '4', '5');

wp_list_filter() is another useful and powerful function that can be used to further refine your new array, say for instance you’d like to create a new array with just cars that are red, this is how you can go about it:

$filter_to_use = array('type' => 'car', 'color' => 'red');
$red_cars = wp_list_filter($vehicles, $filter_to_use);
// this would end up creating an array like so
// array(
//    array(
//        'id' => 1,
//        'type' => 'car',
//        'color' => 'red',
//    ),
//    array(
//        'id' => 3,
//        'type' => 'car',
//        'color' => 'red',
//    )
//);

Both of these functions are very useful when is comes to creating new arrays.

Controlling WordPress Custom Post Types, Capabilities and Roles

We all know about Custom Post Types and how to create them, when it comes to creating generic custom post types without Capabilities all users except subscriber roles can publish, read, edit and delete them by default. What if I refer back to my previous post about roles and limited capabilities for schools and you wanted to create a custom post type that Teachers could read, edit and publish but Staff could only read? Well here’s were custom post types and capabilities gets interesting! Take the following basic custom post type for registering Lessons:

add_action( 'init', 'register_cpt_lesson' );

function register_cpt_lesson() {

    $labels = array( 
        'name' => _x( 'Lessons', 'lesson' ),
        'singular_name' => _x( 'Lesson', 'lesson' ),
        'add_new' => _x( 'Add New', 'lesson' ),
        'add_new_item' => _x( 'Add New Lesson', 'lesson' ),
        'edit_item' => _x( 'Edit Lesson', 'lesson' ),
        'new_item' => _x( 'New Lesson', 'lesson' ),
        'view_item' => _x( 'View Lesson', 'lesson' ),
        'search_items' => _x( 'Search Lessons', 'lesson' ),
        'not_found' => _x( 'No lessons found', 'lesson' ),
        'not_found_in_trash' => _x( 'No lessons found in Trash', 'lesson' ),
        'parent_item_colon' => _x( 'Parent Lesson:', 'lesson' ),
        'menu_name' => _x( 'Lessons', 'lesson' ),
    );

    $args = array( 
        'labels' => $labels,
        'hierarchical' => true,
        'supports' => array( 'title', 'editor' ),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
    );
    register_post_type( 'lesson', $args );
}

The example above would give all users (above subscriber) full capabilities over the custom post type Lessons, meaning all can read, publish, edit and delete them. When we add ‘map_meta_cap, capabilities and capability_type’ to the $args array we can take more control over who gets what capability per role by using the same method referred to in roles and limited capabilities for schools.

Lets modify the $args first by adding map_meta_cap capabilities, and capability_type:

add_action( 'init', 'register_cpt_lesson' );

function register_cpt_lesson() {

    $labels = array( 
        'name' => _x( 'Lessons', 'lesson' ),
        'singular_name' => _x( 'Lesson', 'lesson' ),
        'add_new' => _x( 'Add New', 'lesson' ),
        'add_new_item' => _x( 'Add New Lesson', 'lesson' ),
        'edit_item' => _x( 'Edit Lesson', 'lesson' ),
        'new_item' => _x( 'New Lesson', 'lesson' ),
        'view_item' => _x( 'View Lesson', 'lesson' ),
        'search_items' => _x( 'Search Lessons', 'lesson' ),
        'not_found' => _x( 'No lessons found', 'lesson' ),
        'not_found_in_trash' => _x( 'No lessons found in Trash', 'lesson' ),
        'parent_item_colon' => _x( 'Parent Lesson:', 'lesson' ),
        'menu_name' => _x( 'Lessons', 'lesson' ),
    );

    $args = array( 
        'labels' => $labels,
        'hierarchical' => true,
        'supports' => array( 'title', 'editor' ),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        // map_meta_cap will allow us to remap the existing capabilities with new capabilities to match the new custom post type
        'map_meta_cap' => true
        // capabilities are what we are customising so lets remap them
        'capabilities' => array(
            'edit_post' => 'edit_lesson',
            'edit_posts' => 'edit_lessons',
            'edit_others_posts' => 'edit_other_lessons',
            'publish_posts' => 'publish_lessons',
            'edit_publish_posts' => 'edit_publish_lessons',
            'read_post' => 'read_lessons',
            'read_private_posts' => 'read_private_lessons',
            'delete_post' => 'delete_lesson'
        ),
        // capability_type defines how to make words plural, by default the
        // second word has an 's' added to it and for 'lesson' that's fine
        // however when it comes to words like gallery the plural would become
        // galleries so it's worth adding your own regardless of the plural.
        'capability_type' => array('lesson', 'lessons'),
    );
    register_post_type( 'lesson', $args );
}

So now we have a Custom Post Type with Capabilities remapped to our own custom Capabilities with our own plural words. All we have to do now is add the capability to the role in the same way we did previously with roles and limited capabilities for schools.

Just like so:

function manage_lesson_capabilities() {
    // gets the role to add capabilities to
    $admin = get_role( 'administrator' );
    $editor = get_role( 'editor' );
	// replicate all the remapped capabilites from the custom post type lesson
    $caps = array(
    	'edit_lesson',
    	'edit_lessons',
    	'edit_other_lessons',
    	'publish_lessons',
    	'edit_published_lessons',
    	'read_lessons',
    	'read_private_lessons',
    	'delete_lesson'
    );
    // give all the capabilities to the administrator
    foreach ($caps as $cap) {
	    $admin->add_cap( $cap );
    }
    // limited the capabilities to the editor or a custom role 
    $editor->add_cap( 'edit_lesson' );
    $editor->add_cap( 'edit_lessons' );
    $editor->add_cap( 'read_lessons' );
}
add_action( 'admin_init', 'manage_lesson_capabilities');

Voilà! Not only have we created a neat custom post type we also have complete control over the capabilities the roles have over those custom post types.

Set the WordPress admin colour scheme for different users and roles

Now, under no circumstances should this lovely new feature (3.8) be taken away from users and really this is just for fun however! It could be useful in the real world if you want to give your users some kind of visual representation of their role once they have logged in to a website.
So without any further ado this is how to set the WordPress admin colour scheme for different users and roles:

// note it is a very sad thing to remove these
// color options but useful for roles
function change_admin_color () {
	$users = get_users();
	foreach ($users as $user) {
		if (user_can( $user->ID, 'administrator' )) { // Editor and below
			update_user_meta($user->ID, 'admin_color', 'coffee');
		}
		if (user_can( $user->ID, 'editor' )) { // Editor and below
			update_user_meta($user->ID, 'admin_color', 'sunrise');
		}
		if (user_can( $user->ID, 'author' )) { // Author
			update_user_meta($user->ID, 'admin_color', 'ocean');
		}
		if (user_can( $user->ID, 'contributor' )) { // Contributor and below
			update_user_meta($user->ID, 'admin_color', 'light');
		}
		if (user_can( $user->ID, 'subscriber' )) { // Subscriber and below
			update_user_meta($user->ID, 'admin_color', 'ectoplasm');
		}
	}
	if (!current_user_can('manage_options')) {
		remove_action('admin_color_scheme_picker','admin_color_scheme_picker');
	}
}
add_action('after_setup_theme','change_admin_color');

Again this is really for fun but I hope you can see how useful this might be in the real world 🙂

Create multiple WordPress roles and limited capabilities for Schools

Personally I have set up many school websites and out of the box WordPress has a pretty sophisticated user roles and capabilities authoring engine. This can pretty much apply to any multiple user website but by just considering schools we can break it down in to user chunks.

So, schools have; Students, Staff, Teachers, Deputy Heads and probably a Head who will have more capabilities than others. Using the following code in your functions.php file you can firstly add multiple generic roles then at a later stage give them more capabilities like so:


// add multiple roles with basic capabilities for later use
function add_multiple_roles() {
	$roles = array('head' => 'Head','dep_head' => 'Deputy Head','teacher' => 'Teacher','staff' => 'Staff','student'=>'Student');

	$capabilities = array(
	    'read' => true,  // true allows this capability
	);

	foreach ($roles as $k => $v) {
		add_role( $k, __( $v ),  $capabilities );
	}
}
add_action( 'admin_init', 'add_multiple_roles');

function add_staff_caps() {
    // only relates to staff
    $role = get_role( 'staff' );
	// edit their own posts
    $role->add_cap( 'edit_posts' );
}
add_action( 'admin_init', 'add_staff_caps');

function add_teacher_caps() {
    // only relates to teacher
    $role = get_role( 'teacher' );
	// delete their own posts
    $role->add_cap( 'delete_posts' );
	// edit their own posts
    $role->add_cap( 'edit_posts' );
}
add_action( 'admin_init', 'add_teacher_caps');

function add_dep_head_caps() {
    // only relates to dep_head
    $role = get_role( 'dep_head' );
 	// publish their own posts
    $role->add_cap( 'publish_posts' );
 	// delete their own posts
    $role->add_cap( 'delete_published_posts' );
 	// edit their own published posts
    $role->add_cap( 'edit_published_posts' );
	// edit their own posts
    $role->add_cap( 'edit_posts' );
}
add_action( 'admin_init', 'add_dep_head_caps');

function add_head_caps() {
   $role = get_role( 'head' );
   // do whatever you see fit for the Head to do.....
}
add_action( 'admin_init', 'add_head_caps');

At some point you’ll probably want to change these capabilities but without getting yourself lost down a rabbit hole it’s probably worth mentioning that these capabilities are added to the database and if you think by removing them from your functions.php it is going to work as you would expect – think again!

This is not the case so, to chop and change between capabilities and user roles you’ll have to unregister them or remove them per role it they have been added previously. To show this as an example I’ve commented out the line that previously switch the capability on, if it wasn’t removed from the role it would still retain the capability eg:

function add_head_caps() {
   $role = get_role( 'head' );
   // do whatever you see fit for the Head to do...
   // it was switched on previously and commenting it out will not switch it off...
   // $role->add_cap( 'publish_posts' );
   // if it was previously added then you need to remove it....
   $role->remove_cap( 'publish_posts' );
}
add_action( 'admin_init', 'add_head_caps');

if you get in to a quagmire of not knowing where you are with capabilities you can always debug with the following to see what is going on:

print_r($role = get_role( 'head' ));

Paginate WordPress posts with a thumbnail image

Its always nice to give your users the ability to paginate through your posts, and there are a couple of simple functions that will allow you to do so from with in the individual posts, by that I mean these functions should be used on the single.php template.

By using get_previous_post() and get_next_post() you can retrieve all the information you need from the previous or the next post adjacent to the currently viewed post. If you want to find out more go checkout the codex in the links provided for both functions.

Using the following you can output the link to the previous post of the currently viewed post:

<?php
   $previous = get_previous_post();
   echo get_permalink($previous->ID);
?>

using the get_next_post() you can do the same to get the opposite or get the adjacent post of the currently viewed post like so:

<?php
   $next = get_next_post();
   echo get_permalink($next->ID);
?>

Now that you can access the ID of the previous and next post we can use another function to get the thumbnail of those posts using the get_the_post_thumbnail() function like this:

<?php
    echo get_the_post_thumbnail($previous->ID, 'thumbnail');
?>
<!-- or -->
<?php
    echo get_the_post_thumbnail($next->ID, 'thumbnail');
?>

All you need to do now is to wrap the code up in your mark up to make it your own, putting it all together it might look something like this:

<?php $previous = get_previous_post(); $next = get_next_post(); ?>
<div class="wrapperdiv">
    <div class="float--left">
        <a title="<?php echo esc_attr($previous->post_title); ?>" href="<?php echo get_permalink($previous->ID); ?>">
            <?php echo get_the_post_thumbnail($previous->ID, 'thumbnail'); ?>
        </a>
    </div>
    <div class="float--right">
        <a title="<?php echo esc_attr($next->post_title); ?>" href="<?php echo get_permalink($next->ID); ?>">
            <?php echo get_the_post_thumbnail($next->ID, 'thumbnail'); ?>
        </a>
    </div>
</div>

Your html markup and css should be adapted for your own designs but as long as you are on the single.php template then your users will now be able to paginate WordPress posts with a thumbnail image of the previous and next posts.

A WordPress function to stop non logged in users accessing a page or pages

If you’ve ever tried to build a mini application with WordPress you’ll probably know that you need to use multiple page templates that only registered users can access, so the easiest thing to do is create a WordPress function to stop non logged in users accessing a page or pages, if they can’t then they should get kicked away, gently of course!

Here is one really simple way I’ve used many times to do this.

First of all create this function in your functions.php file

// check users or die
function check_logged_in_users() {
	global $current_user;
	if ( !is_user_logged_in()) {
		wp_die("<p>To access this page you need to login first! Why don't you go back and try again.</p>", "Oh dear, something went wrong!", array( 'response' => 500, 'back_link' => true ));
	} 
}

So next you need to add the function at the top of each page you’d like to hide from non logged in users, somewhere before the get_header() function should do it, looks something like this:

<?php 
/*
	Template Name: This page is for logged in users only
*/
check_logged_in_users();
get_header(); 
?>

Now all page templates with this function will only allow logged in users to access the page.

Create your own registration form in WordPress

From time to time you might need to create your own registration form in WordPress to maintain a brand identity for your client. Although personally I’d be proud to show off the fact that I’m using WordPress, some clients just don’t and they would like their website to reflect their own branding so here’s how we do it.

You can start by putting this form anywhere in one of your theme files but, just to keep things clean I’m going to put this in a new template based on the page.php file so, first of all lets create a new template by duplicating the page.php file and call it something obvious, I’m going to call mine customer-registration.php. Then at the top add the standard template naming comment so you can select the template in the backend of your WordPress installation.

The code at the top of my new page customer-registration.php should look like this:


<?php
/*
   Template Name: Registration Page
*/
get_header();
?>

Next we’ll create the form but, first we need to add an action to hook on too for processing the form as we will be posting it to itself for demonstration purposes, somewhere above the form should be fine.

Then create a simple form with a method of “POST”, an id “adduser”, an empty action so we can post the form to itself and finally some inputs for a Username and Email address. I’ve also included php $error variables for some error checking and you’ll also notice the wp_nonce_field() for extra security after the submit input.

The form code should look something like this:

<?php do_action ('process_customer_registration_form'); ?><!-- the hook to use to process the form -->

<form method="POST" id="adduser" class="user-forms" action="">
	<strong>Name</strong>
	<p class="form-username">
		<label for="user_name"><?php echo 'Username (required)'; ?></label>
		<input class="text-input" name="user_name" type="text" id="user_name" value="" />
	</p>
	
	<p class="form-email">
		<label for="email"><?php echo 'E-mail (required)'; ?></label>
		<input class="text-input" name="email" type="text" id="email" value="" />
	</p>
	
	<p class="form-submit">
		<input name="adduser" type="submit" id="addusersub" class="submit button" value="Register" />
		<?php wp_nonce_field( 'add-user', 'add-nonce' ) ?><!-- a little security to process on submission -->
		<input name="action" type="hidden" id="action" value="adduser" />
	</p>
</form>

Next we’ll need the action function to hook the do_action(‘process_customer_registration_form’) we created at the top of our registration form.

So in your functions.php file add the following code:


function registration_process_hook() {
	if (isset($_POST['adduser']) && isset($_POST['add-nonce']) && wp_verify_nonce($_POST['add-nonce'], 'add-user')) {
	
		// die if the nonce fails
		if ( !wp_verify_nonce($_POST['add-nonce'],'add-user') ) {
			wp_die('Sorry! That was secure, guess you\'re cheatin huh!');
		} else {
			// auto generate a password
			$user_pass = wp_generate_password();
			// setup new user
			$userdata = array(
				'user_pass' => $user_pass,
				'user_login' => esc_attr( $_POST['user_name'] ),
				'user_email' => esc_attr( $_POST['email'] ),
				'role' => get_option( 'default_role' ),
			);
			// setup some error checks
			if ( !$userdata['user_login'] )
				$error = 'A username is required for registration.';
			elseif ( username_exists($userdata['user_login']) )
				$error = 'Sorry, that username already exists!';
			elseif ( !is_email($userdata['user_email'], true) )
				$error = 'You must enter a valid email address.';
			elseif ( email_exists($userdata['user_email']) )
				$error = 'Sorry, that email address is already used!';
			// setup new users and send notification
			else{
				$new_user = wp_insert_user( $userdata );
				wp_new_user_notification($new_user, $user_pass);
			}
		}
	}
	if ( $new_user ) : ?>

	<p class="alert"><!-- create and alert message to show successful registration -->
	<?php
		$user = get_user_by('id',$new_user);
		echo 'Thank you for registering ' . $user->user_login;
		echo '<br/>Please check your email address. That\'s where you\'ll recieve your login password.<br/> (Be sure to check your spam folder)';
	?>
	</p>
	
	<?php else : ?>
	
		<?php if ( $error ) : ?>
			<p class="error"><!-- echo errors if users fails -->
				<?php echo $error; ?>
			</p>
		<?php endif; ?>
	
	<?php endif;

}
add_action('process_customer_registration_form', 'registration_process_hook');

In the function above all we are basically doing is taking the form information and creating a new user from the information given by the user with an auto generated password and sending an email to that user with their login details, we are also making some error checks to make sure the user is created correctly, if there are no errors the user is created with a message telling the new user what to do next, if there are errors we tell the user what has happened so they can try again.

Now you should have a viable registration form that can be placed anywhere on your WordPress installation.

How to create your own custom WordPress login page

Some times you might like to roll your own login page just for that little added bespoke or custom website touch, this is probably easier than you realise! All you need to do is create a custom template and use one of the built in WordPress functions wp_login_form simples! Here’s how to create your own custom WordPress login page.

First of all you need to create a simple custom page template in your theme folder eg: custom-login.php with the following code at the top of your custom page template:

/*
Template Name: Custom Login
*/

Now when you create a new page in the backend you will get the option to use this template as the framework for the page you are creating. So, in this template you will also need the following snippet:


if ( ! is_user_logged_in() ) { // Display WordPress login form for non logged in users:
    $args = array(
        'redirect' =&gt; admin_url(),
        'form_id' =&gt; 'loginform-custom', // give the login form an id for styling the css
        'label_username' =&gt; __( 'Your Username' ),
        'label_password' =&gt; __( 'Your Password' ),
        'label_remember' =&gt; __( 'Remember me on this device' ),
        'label_log_in' =&gt; __( 'Log In' ),
        'remember' =&gt; true
    );
    wp_login_form( $args );
} else { // Otherwise if the users is logged in:
    wp_loginout( home_url() ); // Display &quot;Log Out&quot; link.
    echo &quot; | &quot;;
    wp_register('', ''); // Display &quot;Site Admin&quot; link.
}

Now all you need to do is login to the backend, create a page, select ‘Custom Login’ from the Template dialogue options, preview it and bingo! You’ve just created your own custom and bespoke WordPress login page. You might need to tweak the css styling a little but it will function just like the standard WordPress login page.

Resource: Codex

Track the number of times a WordPress post has been viewed

This is a neat little snippet to track the number of times a WordPress post has been viewed, used wisely it can be used to show a trending post or popular content. In the backend you’ll discover gold gems of content and it can be used to display trending content in the frontend, it could be a blog post, a product, a review or just a popular page that gets a lot of attention! Very useful for your visitors. So, there are a couple of elements to this snippet; a couple of functions and a means to register the data in a post, lets begin…

For the function:

//Track post views without a plugin using post meta
function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return &quot;0 View&quot;;
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

The function above will create a custom field called ‘post_views_count’ attached to the ID of a post that will record the data but, if we have no data a little bit of organic funky creation will happen to create it as zero (0), if it does exist (even if it is 0) we add 1 more view to the data and save it and this is how we clock the views. Sweet eh!

To take advantage of the function we need to register the view in a template or custom post type, this is done by adding the function within the WordPress standard loop so the ID of the post is registered:

    setPostViews(get_the_ID());

To query the content based on views:

$get_trending = array(
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'posts_per_page' => 5
);
$trendy = new WP_Query($get_trending);
while ($trendy->have_posts()) : $trendy->the_post();

echo '<ul><li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li></ul>';

endwhile;
// Reset Post Data
wp_reset_postdata();

hopefully this gives you the gist of this awesome function resource

Get a twitter count of your shared WordPress content without a plugin

If you run a blog that has an audience who regularly share your pages, why not show them the count of how many times your pages have been shared. Here’s how to get a twitter count of your shared WordPress content without a plugin.

function getTweetCount($url)
{
    $url = urlencode($url);
    $twitterEndpoint = &quot;http://urls.api.twitter.com/1/urls/count.json?url=%s&quot;;
    $fileData = file_get_contents(sprintf($twitterEndpoint, $url));
    $json = json_decode($fileData, true);
    unset($fileData); // free memory
    //print_r($json);
    return $json['count'];
}

Add class to search terms for highlighting in WordPress search results

When a user searches your WordPress site it’s nice to give them some feedback on the term they’ve just search, this function will add a class to the search terms you can then use css to highlight the search results.

function wptx_highlight_results($text){
     if(is_search()){
     $sr = get_query_var('s');
     $keys = explode(&quot; &quot;,$sr);
     $text = preg_replace('/('.implode('|', $keys) .')/iu', '&lt;strong class=&quot;search-excerpt&quot;&gt;'.$sr.'&lt;/strong&gt;', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wptx_highlight_results');
add_filter('the_content', 'wptx_highlight_results');
add_filter('the_title', 'wptx_highlight_results');

Source: wpsnipp.com

Have all WordPress user data emailed to site owner on registration

Some sites will have additional user data in the registration form, when users register the site owner is notified by email. Now rather than just getting notified by WordPress that a new user has registered why not have all WordPress user data emailed to site owner on registration, here’s a function that does just that.

function new_user_registered($user_id) {
    global $wpdb;
    $admin_email = get_bloginfo('admin_email');

    if (!current_user_can( 'administrator' )){// avoid sending emails when admin is updating user profiles
        $to = $admin_email;
        $subject = 'Yay! You have a new registered user.';
        $message = &quot;The user has registered with the following user meta data:\n&quot;;
        foreach($_POST as $key => $value){
            $message .= $key . ': '. $value . '\n';
        }
        wp_mail( $to, $subject, $message);
    }
}
add_action( 'user_register', 'new_user_registered');

function yoursite_wp_mail_from($content_type) {
  return 'changethis@mydomain.com';
}
add_filter('wp_mail_from','yoursite_wp_mail_from');

function yoursite_wp_mail_from_name($name) {
  return 'From a Nice Name';
}
add_filter('wp_mail_from_name','yoursite_wp_mail_from_name');

Create a WordPress members role and redirect them to a members area

To create a WordPress members role and redirect them to a members area after login is a simple requirement for many client websites, here are two simple functions to create a new user role, give them some capabilities and redirect them to a members area after they login.

// create a users role with capabilities
$new_member_role = add_role('members', 'Member', array(
    'read' =&gt; true, // True allows that capability
    'edit_posts' =&gt; true,
    'delete_posts' =&gt; false, // Use false to explicitly deny
));

// redirect the users after they login, be sure to create a page with a slug of members-welcome
function wptx_login_redirect_contributors() {
  if ( current_user_can('members') ){
      return '/members-welcome/';
  }
}
add_filter('login_redirect', 'wptx_login_redirect_contributors');

if you need to protect this page from non-logged in users see how to hide a page if a user is not logged in

 

Remove or add additional information to WordPress user profiles

Sometimes the default WordPress user contact details on user profiles are not needed, this sweet little snippet will remove or add additional information to WordPress user profiles; ideal for memberships sites.

function my_user_contactmethods($user_contactmethods){
   // remove contact items
   unset($user_contactmethods['yim']);
   unset($user_contactmethods['aim']);
   unset($user_contactmethods['jabber']);
   // additional contact items
   $user_contactmethods['twitter'] = 'Twitter Username';
   $user_contactmethods['facebook'] = 'Facebook Username';
   return $user_contactmethods;
}

Once saved the user information can be output using the get_user_meta function, the example below is for logged in users…

if ( is_user_logged_in() ) {
// gets all user data
global $current_user;
// gets user meta by id
$user_info = get_user_meta($current_user->ID);
// outputs specific user meta
echo 'Twitter: ' . $user_info['twitter'][0];
echo 'Facebook: ' . $user_info['facebook'][0];
}

source: wp.tuts

Unified text size in the WordPress tag cloud

A simple function to unify the text size of the tag cloud, simply because a non client was getting frustrated with their existing web providers with a “it simply can’t be done.” Well to achieve a unified text size in the WordPress tag cloud here’s how.

add_filter('widget_tag_cloud_args','style_tags');
function style_tags($args) {
$args = array(
     'largest'    => '10',
     'smallest'   => '10',
     'format'     => 'list',
     );
return $args;
}

Get all image attachments from a single WordPress post or page

This is probably one of my personal favorite snippets always very useful for sliders and gallerys, perfect for portfolio items. With this little snippet you’ll get all images attachments from a single WordPress post or page.

<?php
$args = array(
	'order'          => 'ASC',
	'post_type'      => 'attachment',
	'post_parent'    => $post->ID,
	'post_mime_type' => 'image',
	'post_status'    => null,
	'numberposts'    => -1,
);
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $attachment) {
		echo wp_get_attachment_image($attachment->ID, 'custom-image-add-image-size-function');
	}
}
?>

Don’t forget to change ‘custom-image-add-image-size-function’ to your own specific image size.

Source Codex but, I think DIGWP do a better job of explaining this simple snippet.

Remove incorrect WordPress username message during login

Why would you want to remove incorrect WordPress username message during login? Well during login WordPress will notify you if the username or the password is incorrect, if a hacker knows the username they have successfully cracked the login process by 50%. Heres how to remove the message and stop those hackings from finding that information.


function failed_login() {
 return 'The login information you have entered is incorrect.';
}

add_filter('login_errors', 'failed_login');

Now with this in your functions file WordPress will replace the usual message with ‘The login information you have entered is incorrect.’ regardless if they manage to get the username or password correct.

Hide a page if a user is not logged in

Sometimes you might want to hide a page if a user is not logged in. To do this you can use this simple snippet to call a page from within your theme folder called ‘not-logged-in.php’ but, remember this will call before the header, footer and the bits in between so the file that is called should contain the whole code for the page including the html, head and body; opening and closing tags.

<?php
/* Template Name: Only for logged in users */
if ( !is_user_logged_in()) {
get_template_part('not-logged-in');
exit(0);
}
get_header();
?>

the file that’s called might be something like this:

<!DOCTYPE HTML>
<html>
<head>
<title>Ooops! You need to login.</title>
</head>
<body>
<h1>To view this page you need to login.</h1>
</body>
</html>

source: Developing a WordPress site on a live url

Custom WordPress branded login and custom redirects

Do you need a custom WordPress branded login and custom redirects in the dashboard? This snippet will customise the standard WordPress login page, you will need to create a logo and change some of the url parameters to suit your needs. This would be an ideal snippet for a plugin.


// This snippet redirects the login logo upon click
add_filter( 'login_headerurl', 'my_custom_login_url' );
function my_custom_login_url($url) {
 return 'http://www.squareonemd.co.uk';
}

//This snippet allows you to change the logo you see when you login to WordPress(http://website.com/wp-admin). Just put the snippet in functions.php, and then add your login image to a folder called images in your theme folder.

function custom_login_logo() {
 echo '<style type="text/css">
 h1 a { background-image:url(http://www.squareonemd.co.uk/wproute/login-logo.png) !important; }
 </style>';
}
add_action('login_head', 'custom_login_logo');

//Change the alt text for login image
function change_wp_login_title()
{
 echo 'Square One Web and Design';
}add_filter('login_headertitle', 'change_wp_login_title');

//Change the footer link in the admin area
function remove_footer_admin () {
 echo 'Web site design and development by <a href="http://www.squareonemd.co.uk">Square One</a>.';
}
add_filter('admin_footer_text', 'remove_footer_admin');

//Change the header logo in the admin area
function custom_admin_logo() {
 echo '<style type="text/css">
 #header-logo { width:32px; height:32px; background-image: url(http://www.squareonemd.co.uk/wproute/admin-logo.png) !important; }
 </style>';
}
add_action('admin_head', 'custom_admin_logo');

How many more sleeps to go?

Tis the season for giving!! – Here at Square One we want to give all you lovely people a little WordPress something… so simply click on our WordPress advent calendar every day to reveal a useful WordPress code snippet. Or better still simply submit your email and you’ll get them delivered to your inbox daily – after all we know its a busy time of year but we wouldn’t want you to miss out on all of our 25 little gems!

Is it to early to say Merry Christmas?