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
Development Uncategorized

WordPress: How to display posts within a page

We have all been there: for some reason, you really need to display a list of posts within a page in WordPress. And the list needs to be paginated, of course…

Fortunately, there is a way to do it. The WordPress Codex Page reference has a nice (though pretty much buried) example of a page template to get you started:

How to display posts within a page:
http://codex.wordpress.org/Pages#A_Page_of_Posts

As a great addition, it also has an example of a how to display custom post types within a page as well:

How to display a custom post type within a page:
http://codex.wordpress.org/Pages#Using_Custom_Post_Types

I found this definitely helpful, and hopefully you will too!

Happy coding!

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

Extend RSS2: a plugin to enhance your WordPress default RSS2 feed

Hi all,

I just published a new plugin, UW CALS Extend RSS2 Feed (killer name!), and I’m very excited about it.

Basically, this plugin allows you to include thumbnail and custom field information in your WordPress site’s default RSS2 feed, making it more complete.

Give a try! Here’s the link, and let me know what you think!

PS: don’t forget to visit my WordPress Plugins page for more goodies!

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

WordPress: How to display all posts in one page

Although displaying all your latest posts in WordPress may seem like a no-brainer (after all, the default home page already displays your  “Latest Posts”), doing so is kind of tricky if you are trying to do it in on a custom page.

Here’s a little code that can help you accomplish that. Basically, you need to override the $wp_query object with a new query:

<?php 
$wp_query = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish',
'posts_per_page'=>10, 'paged'=>get_query_var('paged')));
?>

Put this code at the beginning of your default  page.php template (or your custom page template) right before the Loop, and you are done!

Categories
Uncategorized

Sample content for WordPress theme development

A big part of the WordPress theme development process is to asses what each possible HTML element will look like (images, tables, lists, paragraphs, etc). The guys at WPCandy.com have put together a set of posts with all the sample content you may need, so you can be thorough in you CSS formatting:

http://wpcandy.com/made/the-sample-post-collection

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