Categories
Development Wordpress

How to create page breadcrumbs in WordPress

Someone at the WordPress StackExchange site was wondering how you could display a list of a page’s ancestors. Pretty much that is the idea of breadcrumbs, so I answered his question using the handy get_ancestors() function.

Below is the code of the function I created to solve the problem. I called it “print_page_parents,” but it might as well be called “page_breadcumbs” =)

Hope you find it useful!

<?php
/**
 * Print list of ancestors in breadcrum fashion, from lowest to highest hierarchy or viceversa.
 *
*/
function print_page_parents($reverse = false){
  global $post;

  //create array of pages (i.e. current, parent, grandparent)
  $page = array($post->ID);
  $page_ancestors = get_ancestors($post->ID, 'page');
  $pages = array_merge($page, $page_ancestors);

  if($reverse) {
    //reverse array (i.e. grandparent, parent, current)
    $pages = array_reverse($pages);
  }

  for($i=0; $i<count($pages); $i++) {
    $output.= get_the_title($pages[$i]);
    if($i != count($pages) - 1){
      $output.= " » ";
    }
  }
    echo $output;
}

//print lowest to highest
print_page_parents();

//print highest to lowest
print_page_parents($reverse = true);

?>

 

Categories
Uncategorized

WordPress: how to automatically convert custom fields to post tags

Hi all,

Sifting through stackoverflow.com I ran into this question: how do you add custom fields automatically as post tags in WordPress?

A while ago, someone asked something similar, and I put together a little script to help, but now I refined that script to be more encompassing. So, here’s a function to add custom fields automatically as post tags.

How it works

The vq20_convert_custom_fields_to_tags() function uses jQuery to retrieve the value of specific custom fields (which you can specify in an array, more on that below), and then adds those to the “tags” list on your post editor on save.

Instructions

  1. Put this script in your functions.php file in your WordPress install:
<?php

function vq20_convert_custom_fields_to_tags(){

    /*create list of custom fields to add as tags on save*/
    $custom_field_names = array();

    if(count($custom_field_names)>0) {?>
        <script type="text/javascript">
            jQuery(document).ready(function($){
            $('form#post').submit(function(event){
            <?php
                foreach($custom_field_names as $name){?>
                    cf_key = $('input[value="<?php echo $name; ?>"]').attr('id').replace('meta[', '').replace('][key]', '');
                    $('#new-tag-post_tag').val($('textarea[id*='+cf_key+']').val());
            <?php } ?>});
            });
        </script>
<?php
    }
}

add_action('admin_footer', 'vq20_convert_custom_fields_to_tags');

?>

 

* * * UPDATE * * *

A couple of  users in the comments below pointed out that the previous code was only adding the last custom field to the tag list, so I decided to go ahead and revamp the whole thing. Use this code instead:

<?php 

function vq20_convert_custom_fields_to_tags(){ ?>

  <script type="text/javascript">
    jQuery(document).ready(function($){      	

    	// Create list of custom fields to add as tags on save
    	// (e.g. var custom_field_names = ['my_custom_field', 'my_other_custom_field', 'yet_another_custom_field'];)
    	var custom_field_names = [];

    	$('form#post').submit(function(){
    		if(custom_field_names.length > 0) {
	    		var custom_field_values = [];
	    		$('#postcustom tr[id^="meta-"]').each(function(){
	    			var meta_id = $(this).attr('id').substring($(this).attr('id').indexOf('-')).replace('-','');
	    			if ($.inArray($(':text[id="meta[' + meta_id + '][key]"]').val(), custom_field_names) !== -1) {
	    				custom_field_values.push($('textarea[id="meta[' + meta_id + '][value]"]').val().toLowerCase());
	    			}
	    		});
	    		var tags = custom_field_values.join(',');
	    		$('#new-tag-post_tag').val(tags);
	    	}
    	});

    });
  </script>
<?php }
add_action('admin_footer', 'vq20_convert_custom_fields_to_tags');

?>

 

  1. Add the names of the custom fields you would like to automatically add as tags to the custom_field_names array
    
    // Create list of custom fields to add as tags on save 
    // (e.g. var custom_field_names = ['my_custom_field', 'my_other_custom_field', 'yet_another_custom_field'];) 
    var custom_field_names = ['my_custom_field', 'my_other_custom_field'];


 

  1. Save/upload your functions.php file, and then go to your post, add the matching custom field(s), and their values should be added as tags as soon as you save the post.

Note: this only works for custom fields holding individual values!!! (i.e. only one value per custom field will be added as a tag)

Let me know what you think!

Happy tagging!

Categories
Uncategorized

How to add the excerpt box for pages in WordPress

By default, the WordPress post editor has an excerpt box that helps you add a little description to your posts. However, this option is not enabled by default for pages, so here’s the solution to that problem.

Add an excerpt meta box to pages

Pre-WordPress 3.0

The best way to add a meta box for pages in WordPress installs older than 3.0 is via the add_meta_box() function.

Add this code to your theme’s functions.php file:

<?php
function add_page_excerpt_support(){
   add_meta_box('postexcerpt', __('Page Excerpt'), 'post_excerpt_meta_box', 'page', 'advanced', 'core');
}

add_action('admin_init', 'add_page_excerpt_support');
?>

The code above tells WordPress to use the same “post_excerpt_meta_box()” callback function it employs to add the excerpt box for regular posts, to enable for pages as well.

 

WordPress 3.0 and up

WordPress 3.0 formally introduced support for new custom post types, which allow you to add custom content types besides the default “post” and “page” types. Along with this, the add_post_type_support() function was added to allow us to tell WordPress what “default” features we want a specific post type to support. Fortunately, we can use this to further extend the default “page” post type as well, such as adding an excerpt box to it.

Add this code to your theme’s functions.php file:

<?php
function add_page_excerpt_support(){
   add_post_type_support( 'page', 'excerpt' );
}

add_action('admin_init', 'add_page_excerpt_support');
?>

And that should be it! Now you should have a spankin’ new excerpt box ready to be filled on your WordPress page editor!

Categories
Uncategorized

WordPress: How to run PHP scripts only when logged in as admin

When developing for WordPress , sometimes you may be looking to run a small piece of code that you and only you can see, without disturbing the peaceful, beautiful flow of your carefully crafted website (and without annoying your users, of course).

So, here’s a small function I created, admin_level(), that’s come in handy several times while I’ve worked with WordPress. By placing this function in your theme’s functions.php file, you will be able to create “test areas” throughout your site where you can run code only when someone with enough permissions (e.g. an “admin” user) is logged in.

NOTE: Testing should ALWAYS be done on a test server separate from production!!! But hey, quick and dirty also does it =)

The admin_level() function

 

<?php
function admin_level($user_login=''){
	global $current_user;
	get_currentuserinfo();

	if(current_user_can('level_10')) {
		if ($user_login!=''){
			if($current_user->user_login==$user_login){
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	} else {
		return false;
	}
}
?>

The admin_level() function has only one optional parameter $user_login, which you can use to basically say “Hey, check that I’m user ‘username’ and have admin access.” If those conditions are met, it returns true, otherwise it returns false.

Examples

Create a “test area” in functions.php

After adding the admin_level()  function to your functions.php file, you can start using it to test things right away. Here’s an example of a “test area” within the function.php file itself (I usually do this at the end of the file, so I know where it is):

<?php

//Test Area

   //Only run following code if logged in as admin

   if( admin_level($user_login = 'vidal') ){

      //run your awesome code right here, admin!!!

   }

//End Test Area

?>

 

Another (inverse) example: redirecting from header.php

Here’s a redirecting script I used on header.php to send anyone who was NOT logged in as admin user ‘vidal’ somewhere else:

<?php

if( !admin_level($user_login = 'vidal') ){

   header('Location:http://www.getouttahere.com);

   exit();
}

?>

This one came in handy, since I needed to temporarily redirect people to another site and keep on working quickly to fix the site ASAP.

 

So, there you have it. This is a very simple way to keep scripts safely confined (even if they fail while you are testing them). I hope you find it useful!

 

 

 

Categories
Uncategorized

Lesson learned: You can’t access DOM elements within an external iFrame

While working with Google Custom Search Engine (CSE), I needed to access elements within the <iframe> containing the search results it generated. Using jQuery, I tried to select the iframe first and its content:

$('#cse-search-results iframe').contents();

But as soon as I tried to do something with it, I’d get a “Error: Permission denied to access property ‘nodeType’” message.

Turns out, <iframes> follow the same origin policy, which prevents you from accessing them directly if they weren’t generated from your own domain. Of course, you can create a proxy file with PHP to retrieve the data first and then add the resulting HTML to your script to get around this problem.

I know, I know… it makes sense now. But I just didn’t know, so, lesson learned!

Categories
Uncategorized

PHP – Safely serialize and unserialze arrays

Serializing arrays in PHP is a great way to format their content before storing it in a database. However, if the serialized content has certain characters (such as “;” or “:”)  the resulting string won’t be read correctly by the unserialize() function,  which is a huge bummer. So, here’s a workaround.

http://davidwalsh.name/php-serialize-unserialize-issues

Categories
Uncategorized

Detect IE6 with PHP

Let’s say you want to server-side detect whether a user’s browser is the dreaded IE6 using PHP (instead of on the client side, which is usually done the conditional comments <!–[if IE 6] –>).

PHP’s function get_browser() is a way to get there, as this function gives you an array or object with info on the user’s browser’s capabilitties. But if you just want a quick and dirty way to find if it’s IE 6 they are using, you can just access the global variable $_SERVER[‘HTTP_USER_AGENT’] to get it done:


<?php 
$using_ie6 = (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== FALSE);
?>


The strpos() function helps you find the position of the string “MSIE 6.” within the string returned by $_SERVER[‘HTTP_USER_AGENT’]. Done.

Credit where credit’s due: http://stackoverflow.com/questions/671890/can-i-detect-ie6-with-php

Categories
Uncategorized

How to automatically add tags to WordPress posts

This one drove me crazy, but I finally figured it out.

In WordPress, if you need to automatically add tags to a post via a PHP script, the best way to do it is via the wp_set_object_terms() function. There is no handy “wp_insert_tag()” function, or something like that, so look no further.

wp_set_object_terms()

wp_set_object_terms() is a powerful function that not only helps you assign tags to posts (or pages), but also categories and other terms. For this example, here’s the PHP code needed to assign tags to a post.

<?php
   $tags = array('html', 'css', 'javascript');
   wp_set_object_terms( $post_id, $tags, 'post_tag', true );
?>

The code above will create the new tags (or terms) if they don’t exist and link them to the post specified by $post_id.

For more info on this function and its parameter, check out the codex page at http://codex.wordpress.org/Function_Reference/wp_set_object_terms/

Categories
Uncategorized

How to automatically login a user into WordPress

When developing for WordPress, sometimes you may need to create a PHP script that will automatically login a user so you can enable user functions. I needed to do something like that when creating a public form to submit posts from the front end using Ajax. The WorpPress function wp_singon() was the perfect solution.

wp_signon()

The wp_signon() function takes the user account’s username and password as parameters, and will allow you to set up a secure cookie for the new session. For more info, check out the function’s codex page: http://codex.wordpress.org/Function_Reference/wp_signon

Another way to auto-login:

Cleverwp.com has an interesting post on how to Autologin a WordPress user in your PHP script which only requires the user’s login name. It’s pretty straight forward, though not as secure.

Categories
Uncategorized

How to get the ID of the last insert post in WordPress

When programming for WordPress, sometimes you may need to get the ID of the last post that was inserted to the database (à la MySQL’s ‘LAST_INSERT_ID’).  Here’s the thing: the wp_insert_post() function returns the newly inserted post’s ID, so you can use it to perform more stuff on the post right away, without having to mess around with any SQL commands to retrieve it. Clever, huh?

wp_insert_post()

The function wp_insert_post() does that, it inserts posts into the WP database. You only need to create a required object (or array) containing  a few  properties of the new post (such as post_title, post_content, post_status, etc) to get it rolling, and it will fill in any blanks you might’ve missed.

But the main point here is that the wp_insert_post() function returns the newly inserted post’s ID.

Here’s an example:

<?php

//insert new post
 // Create post object
 $my_post = array();
 $my_post['post_title'] = 'Hello world';
 $my_post['post_content'] = 'This is a sample post';
 $my_post['post_status'] = 'published';
 $my_post['post_author'] = 7; //the id of the author
 $my_post['post_category'] = array(10,12); //the id's of the categories

 // Insert the post into the database
 $post_id = wp_insert_post( $my_post ); //store new post id into $post_id

?>

Now the $post_id variable contains the id of the last inserted post, and you can use it in the rest of your script.  For example, we could use it now to assign tags to the recently added post:

<?php

//now add tags to new post using the last inserted post id in the $post_id var
 $tags = array('html', 'css', 'javascript');
 wp_set_object_terms( $post_id, $tags, 'post_tag', true );    

?>

Cool, huh?

For more info on the wp_insert_post() function visit check the codex page at: http://codex.wordpress.org/Function_Reference/wp_insert_post

Getting last insert id from the $wpdb object:

The $wpdb object stores the last insert post id as a property. I tried using it and it didn’t work for me, but you can still try to use it. Here’s the codex page:

http://codex.wordpress.org/Function_Reference/wpdb_Class#Class_Variables