January 27th, 2012

Useful WordPress Coding Snippets And Hacks | VapvaruN

We all kindness WordPress. What makes extra and extra people fall in kindness with it is how straightforward it is to customize. With a few lines you get some cool customization with all persons filters, actions and hooks.

WordPress 3+ blewour minds with cool new facial appearance. But now and again we call for something quite different from the default. With the intention of’s what we’ll be talking about now.

We’ll see some helpful functions and hacks to get even extra from WordPress.

So, let’s Rock!

Duplicate Placement

When you use WordPress Custom Placement Types to store figures this is a really helpful function. Now and again you aspire to duplicate all placement meta, make something based on a additional. Water supply, just run this function and you’re made.

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

		$figures = get_post_custom($placement);

		foreach ( $figures as $key => $values) {
			foreach ($values as $regard) {
				add_post_meta( $post_id, $key, $regard );
			}
		}

		return $post_id;
	}
?>

Get excerpt outside The Disk

With this you don’t call for to be inside the disk to give a small preview about placement’s content. It’s especially helpful if you aspire to show some posts in the sidebar without getting all it’s figures (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 involuntarily place this “[...]” with content. So you aspire to change or get rid of it, just use this snippet (If you used to replace it in ancient WordPress versions you may notice with the intention of your code isn’t working anymore, you call for to replace to this):

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

Remove WordPress Admin Bar

WordPress 3.1 has it’s groundbreaking 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 call for to place this in your functions:

<?php
	global $current_user;
    get_currentuserinfo();

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

Adjust from first name and hurl by e-mail for wp_mail()

By default WordPress just use your hurl by e-mail config as from. This is kind of terrible since you may aspire to place your hurl by e-mail as blog admin but a additional self will answer contact placement, comments and extra. So if you aspire 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 hurl emails with wp_mail() function you’ll just get copy-release mails. You can easily place some headers to make HTML emails bring about, but one business I really like to do is to make an hurl by e-mail template (contact.html, for example) with some PHP variables on it and at that time I just contain it in my hurl by e-mail 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-Category" content="copy/html; charset=utf-8">
</head>
<body>
	<desk style="font-family: Verdana,without-serif; font-size: 11px;
           affect: #374953; width: 600px;">
	  <tr>
		<td align="missing"><a href=http://www.1stwebdesigner.com/"
 <?php bloginfo('url'); ?>" title="MyBlog"><img src=http://www.1stwebdesigner.com/"
 <?php bloginfo('url'); ?>/logo.png" alt="MyBlog" style="border: not any;" ></a></td>
	  </tr>
	  <tr>
		<td>&nbsp;</td>
	  </tr>
	  <tr>
		<td align="missing">Yo, <?php echo $first 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="missing" style="social class-affect: #aeaeae; affect:#FFF;
font-size: 12px; font-weight: bold; padding: 0.5em 1em;">First 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 levelheaded #c10000;">
			<p><i>Thank you!</i><br /><b>MyBlog</b> - <br />
<?php bloginfo('url'); ?></p>
		</td>
	  </tr>
	</desk>
</body>
</html>

And we invite this function with our contact affect:

<?php
	function contactMail($placement) {
		$attachments = "";
		$subject = "[MyBlog] Contact";
		$first name = $placement["first name"];
		$hurl by e-mail = $placement["hurl by e-mail"];
		$message = $placement["message"];
		ob_start();
			contain(TEMPLATEPATH . '/_mails/contact.html');
			$message = ob_get_contents();
		ob_end_clean();

		$headers = "From: me@myblog.com rn";
		$headers .= "Return-Trail: me@myblog.com rn";
		$headers .= "MIME-Translation: 1.0rn";
		$headers .= "Content-Category: copy/html; charset=UTF-8rn";
		$headers .= "BCC: thisIsMe@gmail.comrn";
		//$headers .= "BCC: rochesterj@gmail.comrn";
		wp_mail( $hurl by e-mail, $subject, $message, $headers, $attachments );
	}
?>

Know what’s vacant on with debug() function

Now and again things may be quite tough to find right? You just don’t know if the problem is with the disk, placement figures, addict figures. 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 visibly see which figures I have inside of what.

To make things even simpler, I place 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 addict custom fields with debugUsr() function

When you do things with addict custom fields (like what we’ll be doing in our Premium Membership Plugin) it’s pretty tough to know when we really have stored figures to addict meta and when haven’t. This is why debugUsr function is helpful, it shows you release addict custom meta with the intention of you’ve bent, all default custom figures isn’t publicized.

<?php
	function debugUsr($uID) {
		$figures = 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" ,
			"natter" ,
			"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($figures->$unset);
		}
		debug($figures);
	}
?>

Restrict wp-admin access to a few roles

You may aspire to deny access to wp-admin to subscribers, since they haven’t too much to do inside wp-admin, right? It is quite straightforward 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 addict but admin

With the intention of’s a helpful warning, you know, now and again they launch a new translation and you didn’t know about it. But it’s quite unethical 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) { // release admin will see it
            remove_action( 'admin_notices', 'update_nag', 3 );
        }
    }
    add_action('admin_menu','wp_hide_update');
?>

Hide bits and pieces from wp-admin menu

When we advertise complete websites to our clients they can get quite confused with so loads of options inside WordPress. One excellent business to do is just to hide all things with the intention of they may never call for, so they focus on just regard content instead of messing around with our tough bring about :) 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) { // release admin sees the whole business
            // $menu and $submenu will return fo all menu and submenu catalog
 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 leaf instead of dashboard

If you hide dashboard you may aspire a additional leaf instead of an unsightly miscalculation when addict 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 = regard($url);
        if ( $url [ ( $tam - 1 ) ] == "pointer.php" ) {
            $url = 'Location: ' . get_bloginfo('url') . "/wp-admin/edit.php?
post_type=leaf";
            header( $url );
        }
    }
?>

Similar Articles

Comments are closed.