12 Useful WordPress Coding Snippets And Hacks

We all love WordPress. What makes more and more people fall in love with it is how easy it is to customize. With a few lines you get some cool customization with all those filters, actions and hooks.

WordPress 3+ blewour minds with cool new features. But sometimes we need something quite different from the default. That’s what we’ll be talking about today.

We’ll see some useful functions and hacks to get even more from WordPress.

So, let’s Rock!

Duplicate Post

When you use WordPress Custom Post Types to store data this is a really useful function. Sometimes you want to duplicate all post meta, create something based on another. Well, just run this function and you’re done.

<?php
	function duplicate($post) {
		$title =  get_the_title($post);
		$post = array(
			'post_title' => $title,
			'post_status' => 'publish',
			'post_type' => 'post',
			'post_author' => 1
		);
		$post_id = wp_insert_post( $post );

		$data = get_post_custom($post);

		foreach ( $data as $key => $values) {
			foreach ($values as $value) {
				add_post_meta( $post_id, $key, $value );
			}
		}

		return $post_id;
	}
?>

Get excerpt outside The Loop

With this you don’t need to be inside the loop to give a little preview about post’s content. It’s especially useful if you want to display some posts in the sidebar without getting all it’s data (just title, link and excerpt, for example).

<?php
	function get_excerpt_outside_loop($post_id) {
		global $wpdb;
		$query = 'SELECT post_excerpt FROM '. $wpdb->posts .' WHERE ID = '. $post_id .' LIMIT 1';
		$result = $wpdb->get_results($query, ARRAY_A);
		$post_excerpt=$result[0]['post_excerpt'];
		return $post_excerpt;
	}
?>

Replace “[...]” string with the_excerpt()

When you use the_exerpt() WordPress automatically put this “[...]” after content. So you want to change or get rid of it, just use this snippet (If you used to replace it in old WordPress versions you may notice that your code isn’t working anymore, you need to replace to this):

<?php
	function new_excerpt_more($more) {
		return '[much more to go]';
	}
	add_filter('excerpt_more', 'new_excerpt_more');
?>

Remove WordPress Admin Bar

WordPress 3.1 has it’s brand new admin bar. If you just updated your WP you may notice a couple of issues with it (for my custom theme it just added an extra padding at top, but wasn’t calling the bar itself). To remove it you just need to put this in your functions:

<?php
	global $current_user;
    get_currentuserinfo();

    if ($current_user->ID != 1) {
        add_filter( 'show_admin_bar', '__return_false' );
    }
?>

Adjust from name and email for wp_mail()

By default WordPress just use your email config as from. This is kind of bad because you may want to put your email as blog admin but another person will answer contact messages, comments and more. So if you want to change default settings for this, just use this snippet:

<?php
	function mail_from() {
		$emailaddress = 'contact@1stwebdesigner.com';
		return $emailaddress;
	}

	function mail_from_name() {
		$sendername = "1stWebDesigner.com - Dainis";
		return $sendername;
	}

	add_filter('wp_mail_from','mail_from');
	add_filter('wp_mail_from_name','mail_from_name');
?>

HTML Emails with wp_mail()

By default if you try to send emails with wp_mail() function you’ll just get text-only mails. You can easily put some headers to make HTML emails work, but one thing I really like to do is to create an email template (contact.html, for example) with some PHP variables on it and then I just include it in my email function. This is how my template looks like:

<?php
	function mail_from() {
		$emailaddress = 'contact@1stwebdesigner.com';
		return $emailaddress;
	}

	function mail_from_name() {
		$sendername = "1stWebDesigner.com - Dainis";
		return $sendername;
	}

	add_filter('wp_mail_from','mail_from');
	add_filter('wp_mail_from_name','mail_from_name');
?>
<html></span></h2>
<pre><head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
	<table style="font-family: Verdana,sans-serif; font-size: 11px; color: #374953; width: 600px;">
	  <tr>
		<td align="left"><a href="<?php bloginfo('url'); ?>" title="MyBlog"><img src="<?php bloginfo('url'); ?>/logo.png" alt="MyBlog" style="border: none;" ></a></td>
	  </tr>
	  <tr>
		<td>&nbsp;</td>
	  </tr>
	  <tr>
		<td align="left">Yo, <?php echo $name; ?>.<br />How are you?</td>
	  </tr>
	  <tr>
		<td>&nbsp;</td>
	  </tr>
	  <tr>
		<td>I've recieved your message and we'll answer it soon!</td>
	  </tr>
	  <tr>
		<td>&nbsp;</td>
	  </tr>
	  <tr>
		<td align="left" style="background-color: #aeaeae; color:#FFF; font-size: 12px; font-weight: bold; padding: 0.5em 1em;">Original Message</td>
	  </tr>
	  <tr>
		<td><?php echo $message; ?></td>
	  </tr>
	  <tr>
		<td>&nbsp;</td>
	  </tr>
	  <tr>
		<td align="center" style="font-size: 10px; border-top: 1px solid #c10000;">
			<p><i>Thank you!</i><br /><b>MyBlog</b> - <br /><?php bloginfo('url'); ?></p>
		</td>
	  </tr>
	</table>
</body>
</html>

And we call this function with our contact form:

<?php
	function contactMail($post) {
		$attachments = "";
		$subject = "[MyBlog] Contact";
		$name = $post["name"];
		$email = $post["email"];
		$message = $post["message"];
		ob_start();
			include(TEMPLATEPATH . '/_mails/contact.html');
			$message = ob_get_contents();
		ob_end_clean();

		$headers = "From: me@myblog.com \r\n";
		$headers .= "Return-Path: me@myblog.com \r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
		$headers .= "BCC: thisIsMe@gmail.com\r\n";
		//$headers .= "BCC: rochesterj@gmail.com\r\n";
		wp_mail( $email, $subject, $message, $headers, $attachments );
	}
?>

Know what’s going on with debug() function

Sometimes things may be quite hard to find right? You just don’t know if the problem is with the loop, post data, user data. With print_r you may see things pretty (like php.net does), but if you do this in your theme, with your own formatting, the return code is probably unreadable. So what I usually do is wrap this with <pre> so I can clearly see which data I have inside of what.

To make things even easier, I put this inside one function in my functions.php so it helps me a lot:

<?php
	function debug($var) {
		if ( ! is_string($var) ) {
			echo "<pre>";
				print_r($var);
			echo "</pre>";
		} else {
			echo "DEBUG: ".$var;
		}
	}
?>

See user custom fields with debugUsr() function

When you do things with user custom fields (like what we’ll be doing in our Premium Membership Plugin) it’s pretty hard to know when we really have stored data to user meta and when haven’t. This is why debugUsr function is useful, it shows you only user custom meta that you’ve created, all default custom data isn’t shown.

<?php
	function debugUsr($uID) {
		$data = get_userdata($uID);

		$unsets = Array (
			"ID",
			"user_login",
			"user_pass",
			"user_nicename",
			"user_email",
			"user_url" ,
			"user_registered",
			"user_activation_key" ,
			"user_status",
			"display_name" ,
			"first_name" ,
			"last_name" ,
			"nickname",
			"description" ,
			"rich_editing" ,
			"comment_shortcuts",
			"admin_color" ,
			"use_ssl" ,
			"show_admin_bar_front",
			"show_admin_bar_admin",
			"aim" ,
			"yim" ,
			"jabber" ,
			"wp_capabilities",
			"wp_user_level" ,
			"wp_usersettings" ,
			"wp_usersettingstime" ,
			"wp_dashboard_quick_press_last_post_id" ,
			"nav_menu_recently_edited" ,
			"managenavmenuscolumnshidden" ,
			"metaboxhidden_navmenus" ,
			"metaboxorder_d_offer" ,
			"screen_layout_d_offer" ,
			"plugins_last_view",
			"user_level" ,
			"user_firstname" ,
			"user_lastname" ,
			"user_description"
		);
		foreach ( $unsets as $unset) {
			unset($data->$unset);
		}
		debug($data);
	}
?>

Restrict wp-admin access to a few roles

You may want to deny access to wp-admin to subscribers, since they haven’t too much to do inside wp-admin, right? It is quite easy to deny access to them, just use this snippet:

<?php
	function restrict_access_admin_panel(){
		global $current_user;
		get_currentuserinfo();

		if ($current_user->user_level <  4) { //if not admin, die with message
			wp_redirect( get_bloginfo('url') );
			exit;
		}

	}
	add_action('admin_init', 'restrict_access_admin_panel', 1);
?>

Hide update warning for every user but admin

That’s a useful warning, you know, sometimes they launch a new version and you didn’t know about it. But it’s quite unprofessional if your client or even subscribers know about it, right? So why not just show them to blog admin? Use this:

<?php
function wp_hide_update() {
        global $current_user;
        get_currentuserinfo();

        if ($current_user->ID != 1) { // only admin will see it
            remove_action( 'admin_notices', 'update_nag', 3 );
        }
    }
    add_action('admin_menu','wp_hide_update');
?>

Hide items from wp-admin menu

When we sell complete websites to our clients they can get quite confused with so many options inside WordPress. One good thing to do is just to hide all things that they may never need, so they focus on just adding content instead of messing around with our hard work :) With this function you hide a lot of things. Try different combinations of numbers and see what will be hidden:

<?php
    function remove_dashboard_widgets() {
        global $menu,$submenu;

        global $current_user;
        get_currentuserinfo();

        if ($current_user->ID != 1) { // only admin sees the whole thing
            // $menu and $submenu will return fo all menu and submenu list in admin panel .
            $menu[2] = ""; //Dashboard
            $menu[5] = ""; // Posts
            $menu[15] = ""; //Links
            $menu[25] = ""; //Comments
            $menu[65] = ""; //Plugins

            unset($submenu['themes.php'][5]); //themes
            unset($submenu['themes.php'][12]); //editor
        }
    }
    add_action('admin_head', 'remove_dashboard_widgets');
?>

Redirect for different page instead of dashboard

If you hide dashboard you may want another page instead of an ugly error when user goes to wp-admin, right? So we can redirect them when they try to access just wp-admin:

<?php
	if ( is_admin() ) {
        $url = $_SERVER['SCRIPT_NAME'];
        $url = explode('/', $url);
        $tam = count($url);
        if ( $url [ ( $tam - 1 ) ] == "index.php" ) {
            $url = 'Location: ' . get_bloginfo('url') . "/wp-admin/edit.php?post_type=page";
            header( $url );
        }
    }
?>

What do you think?

Well, we have here some of the functions that I use most. What about you? Do you know something that I missed? Share it via comments! :)

Rochester Oliveira

I'm a web designer and entrepreneur from Itajubá (MG), Brasil. I love writing about obscure topics and doing some cool stuff. And also I do some FREE stuff, check it out: http://www.roch.com.br/

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. says

    This function which you have shared “HTML Emails with wp_mail()”, is going to be very useful for me. Thanks for sharing such a wonderful things.

    • says

      Hi Paul!

      That’s probably because you’re admin. But subscribers won’t use it that much, probably.. That’s why I’ve changed it to show only for admin :)

      []’s

  2. says

    Thanks for compiling this list! Do you know of a website with more of this easy to copy and really usefull snippets? Kind of a database full of handy addons for WordPress developers?

  3. Andrew Groat says

    Wow, I can’t believe I didn’t know about some of this.

    Very excited to dig into the wp_mail() and debug() functions!

    Great work!

  4. Craig says

    Love the small debug function. For years I have been using a nearly identical one I call print_r_pre() for outputting pre-formatted arrays.

  5. Shaquil Oliver says

    Word press alows things to be hidden and you can always go back to open it. It’s perfect for websites that are created for a specific person or group.