WordPress Functions and Scripts That I Recently Used

Written by Kevin Liew on 27 Jun 2013
19,933 Views • WordPress

I have just completed another WordPress website that requires a few custom post types, custom registration, edit profile and login with front-end design. I found myself getting better and better in WordPress development now.

Previously, I shared about WordPress Custom Posts. Today, I want to share a few functions and code snippets that I used in this most recent project. To be completely honest, I'm not the author of these scripts, because I copied it and used it during development. Therefore, I've lost track of the original author. So, I would like to give credit to the WordPress community - Thanks for sharing these awesome codes!

This time I have a breakthrough in building a custom registration, edit profile and login forms. Previously I relied on Profile Builder Pro. It's powerful and do exactly what I want, but one thing that really suck - You don't have the control over its design layout and HTML markup. I need a two column registration form. I know I can do it by hacking the plugin, but that always not the best way as I will lost all my changes once the plugin is updated. However, I'm still using its forgotten password because it's just too time consuming to build it myself!

Similar with previous project, I built the website by using Bones WordPress HTML5 Boilerplate. A good time saver and a lot of custom scripts in it too.

Alright, here are some of the useful functions and scripts I used throughout the development and I hope it will help you too.

 

Define Thumbnail size

You can predefine different thumbnail sizes so you can reuse them in the website. Put this in functions.php.

add_image_size( 'custom-thumb-960', 940, 327, true );
add_image_size( 'custom-thumb-600', 600, 150, true );
add_image_size( 'custom-thumb-300', 300, 100, true );

This is how to use it:

<?php 
	the_post_thumbnail('custom-thumb-212');
?> 

 

Login with Email Address

This hook will override WordPress login and allow user to type in email as username. Put this in functions.php.

function login_with_email_address($username) {
	$user = get_user_by_email($username);
	if(!empty($user->user_login))
		$username = $user->user_login;
	return $username;
}
add_action('wp_authenticate','login_with_email_address');	

 

Contact Form 7

Alright, I guess most of you must have heard of Contact Form 7 or using it at the moment. Not sure if you know it, CF7 actually is loaded( all the Javascript and CSS files) all the time even through there is no CF7 forms. These two functions change that, but you will need to specify the post ID or page ID.

If you only used it as contact us form, yes, these will be a great functions to speed up your WordPress website a little bit more. Put this in functions.php

//load contact-form-7 on contact page only
add_action( 'wp_print_scripts', 'deregister_cf7_javascript', 100 );
function deregister_cf7_javascript() {
    if ( !is_page(PAGE_ID_PUT_HERE) ) {
        wp_deregister_script( 'contact-form-7' );
    }
}

add_action( 'wp_print_styles', 'deregister_cf7_styles', 100 );
function deregister_cf7_styles() {
    if ( !is_page(PAGE_ID_PUT_HERE) ) {
        wp_deregister_style( 'contact-form-7' );
    }
}	

 

Excerpt and Content Text limit

I need to have excerpt to be output in different lengths in different sections of the website. I found these functions that do the word count and output it for me. Put this in functions.php.

function excerpt($limit) {
  $excerpt = explode(' ', get_the_excerpt(), $limit);
  if (count($excerpt)>=$limit) {
    array_pop($excerpt);
    $excerpt = implode(" ",$excerpt).'...';
  } else {
    $excerpt = implode(" ",$excerpt);
  } 
  $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
  return $excerpt;
}

function content($limit) {
  $content = explode(' ', get_the_content(), $limit);
  if (count($content)>=$limit) {
    array_pop($content);
    $content = implode(" ",$content).'...';
  } else {
    $content = implode(" ",$content);
  } 
  $content = preg_replace('/\[.+\]/','', $content);
  $content = apply_filters('the_content', $content); 
  $content = str_replace(']]>', ']]&gt;', $content);
  return $content;
}	

 

Create User

Front-end registration form. Part of the requirement of my project is that the registration form should have custom fields and should inherit the website design as well. I created a page called "Register" and make custom page for it (page-register). By going down this path, I will need to validate all the fields and create users via WordPress built-in functions.

Basically, this is the code that validates, create user, create meta field and auto login once completed. Credit to Cristian Antohe.

<?
/* Load registration file. */
require_once( ABSPATH . WPINC . '/registration.php' );
 
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'adduser' ) {

	// Get all the form field. I named my form elements form[username], form[firstname]
	$form = $_POST['form'];
 
	if ( !$form['username'] ) {
		$errors[count($errors)] = 'A username is required for registration.';
	} elseif (strlen($form['username']) <3) {
		$errors[count($errors)] = 'Sorry, username has to be at least 3 characters.';
	} elseif ( username_exists($form['username']) ) {
		$errors[count($errors)] = 'Sorry, that username already exists.';
	}
	
	if ( !is_email($form['email'], true) ) {
		$errors[count($errors)] = 'You must enter a valid email address.';
	} elseif ( email_exists($form['email']) ) {
		$errors[count($errors)] = 'Sorry, that email address is already used.';
	}

	if ($form['password']) {	
		if ( strlen($form['password']) <=5 ) {
			$errors[count($errors)] = 'Password must be minimum 6 characters';
		} elseif ( $form['password'] != $form['repassword'] ) {
			$errors[count($errors)] = 'Passwords do not match.';
		}	
	}
	
	if (!isset($form['gender'])) {
		$errors[count($errors)] = 'Please choose your gender.';	
	}
	
	if (!isset($form['terms'])) {
		$errors[count($errors)] = 'You must agree to our terms and conditions.';	
	}	
	
	// Proceed to user creation if no errors were found
	if (!$errors) {

		$userdata = array(
			'user_pass' => $form['password'],
			'user_login' => esc_attr( $form['username'] ),		
			'first_name' => esc_attr( $form['firstname'] ),
			'last_name' => esc_attr( $form['lastname'] ),
			'user_email' => esc_attr( $form['email'] ),
			'gender' => esc_attr( $form['gender'] )
		);	
	
		// This is the core function to create an user
		$new_user = wp_insert_user( $userdata );
		
		// Send email notification
		wp_new_user_notification($new_user, $form['password']);
 
		// If you have custom fields, this is how you add custom user meta fields
		update_user_meta( $new_user, 'gender',     esc_attr( $form['gender'] ));
		update_user_meta( $new_user, 'dob',        esc_attr( $form['dob'] ));
		update_user_meta( $new_user, 'address1',   esc_attr( $form['address1'] ));
		update_user_meta( $new_user, 'address2',   esc_attr( $form['address2'] ));
		update_user_meta( $new_user, 'city',       esc_attr( $form['city'] ));
		update_user_meta( $new_user, 'state',      esc_attr( $form['state'] ));
		update_user_meta( $new_user, 'postcode',   esc_attr( $form['postcode'] ));
		update_user_meta( $new_user, 'phone',      esc_attr( $form['phone'] ));		
		update_user_meta( $new_user, 'newsletter', esc_attr( $form['newsletter'] ));		
		update_user_meta( $new_user, 'terms',      esc_attr( $form['terms'] ));						
		
		// This to ensure the admin bar is hidden after the user login as subscriber
		update_user_meta( $new_user, 'show_admin_bar_front',   esc_attr( 'false' ));		
				
		// Auto login		
		if ($new_user) {				
	    $creds = array();
	    $creds['user_login'] = $form['username'];
	    $creds['user_password'] = $form['password'];
	    
	    if ( !empty( $remember ) ) { 
	        $creds['remember'] = true;
	    }
	    $user = wp_signon( $creds, true );

			// Once login, redirect user to thank you page or profile page
	    wp_redirect( '/thank-you/' );
	    exit;
		}				
				
	} 		
}
?>

Underneath this PHP script, it should be the <? get_header() ?>, HTML Layout and Form field, and lastly <? get_footer ?>.

 

Edit User

So, if you have a registration page, the chances are, your user will need to edit their own profiles. Similar to registration, we create another page called "Profile", then we give it a custom content page by creating "page-profile" in theme folder. You still need to do validations and include WordPress registration.php, but here I won't go into detail, this is just the crucial part of the code that update user details.

......

$userdata = array(
	'ID' => $user_id,
	'first_name' => esc_attr( $form['firstname'] ),
	'last_name' => esc_attr( $form['lastname'] ),
	'user_email' => esc_attr( $form['email'] ),
	'gender' => esc_attr( $form['gender'] )
);	

// Update user
wp_update_user($userdata);

// Update meta fields
update_user_meta( $user_id, 'gender',     esc_attr( $form['gender'] ));
update_user_meta( $user_id, 'dob',        esc_attr( $form['dob'] ));
update_user_meta( $user_id, 'address1',   esc_attr( $form['address1'] ));
update_user_meta( $user_id, 'address2',   esc_attr( $form['address2'] ));
update_user_meta( $user_id, 'city',       esc_attr( $form['city'] ));
update_user_meta( $user_id, 'state',      esc_attr( $form['state'] ));
update_user_meta( $user_id, 'postcode',   esc_attr( $form['postcode'] ));
update_user_meta( $user_id, 'phone',      esc_attr( $form['phone'] ));	

......		

 

Auto Login and Login form

I found 2 solutions that able to perform auto login. The first one is rather strange that you can login as different users without knowing its user password. I guess that's useful for site admin.

require('wp-blog-header.php');
$user_login = 'kevin7';
$user = get_userdatabylogin($user_login);
$user_id = $user->ID;
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id);
do_action('wp_login', $user_login);

This is a more common method most people are using. You can create a custom login page with this by passing username and password as POST form submission.

$creds = array();
$creds['user_login'] = 'USERNAME';
$creds['user_password'] = 'PASSWORD';

if ( !empty( $remember ) ) { 
    $creds['remember'] = true;
}
$user = wp_signon( $creds, true );

That's all for now

I found myself really please with what WordPress can do. I ain't a hardcore PHP developer, but the way WordPress was built, its flexibility and its robust WordPress community have really made my life heaps lot easier! Do you have any killing code snippets that you always use during the development? Share with me!

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

5 comments
Connie 11 years ago
Kevin,

not to loose track to the original author, it is good practice to add one commentary line with the URL and name of the author above each snippet

thus you will keep the track and can give the credits to the author ;=)
Reply
Kevin Admin 11 years ago
Yep, noted :)
Reply
bucur 11 years ago
Very good these codes you use at least the first me help me, thanks Kevin...
Reply
Adam Jhon 11 years ago
WordPress has various functions and functions which are used frequently in development. These are basic elements and every developer should grip on them. Thanks for sharing!

Website designers Vancouver http://www.designcrews.com/website-design.html
Reply
loicuoi 11 years ago
thank you very much, nice tut :)
Reply