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

Hadoop, MapReduce and processing large Twitter datasets for fun and profit

This fall I just enrolled back to complete my PhD at the School of Journalism and Mass Communications (SJMC) at the University of Wisconsin-Madison. As part of my activities, I’ve been attending the sessions of the Social Media and Democracy research group at SJMC, a great collaborative effort to further research in Social Media and how it’s used in political communications.

As part of a series of upcoming research projects on a HUGE Twitter dataset collected SMAD  during the US 2012 presidential election, we’ve been brushing up on Python, Hadoop and MapReduce. I’m very excited about this opportunity, as big data analysis seems to be coming of age and gaining traction on in several areas of communication research.

Getting started with Hadoop and MapReduce

As part of our training, Alex Hanna, a sociology PhD student at UW-Madison, put together an excellent series of workshops on Twitter (or, as he’s aptly named them,  “Tworkshops“) to get the whole SMAD team started in the art of big data analysis. It’s an excellent reference for beginners, so if you are interested in analyzing Twitter data, this is definitely for you:

Thanks to Alex for all his time and effort. This is all incredibly cool, and I’m looking forward to continue exploring our dataset and learning more about Hadoop and MapReduce!

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

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

My response to Stackoverflow’s ““invalid label” Firebug error with jQuery getJSON” question

“Invalid label” Firebug error with jQuery getJSON

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

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 center divs within a page with CSS

Sometimes you may want to center a div element within a page, whether vertically, horizontally, or both (dead center). Here’s how  you can accomplish all of that using CSS.

What you need:

The HTML

For this example, we’ll use the following HTML code:

<div id="container">
<p>Some content goes here.</p>
</div>

The CSS

The basic formatting for the #container element will be:

#container {
border: 1px solid #000;
background-color: #69C;
padding: 8px;}

Getting it done:

How to center a div element horizontally

To center a div element horizontally you need to:

  1. Set its left and right margins to auto,  which will automatically set the margin space on both sides of the div element, centering it within the page.
  2. Declare the div element’s width to override the default width: auto property, which makes div elements be as wide as their containers .
Here’s the CSS:
.center_horiz{
 width: 158px;
 margin: 0 auto;
}

See example here

How to center a div element vertically

To center a div element vertically vertically within a page, you need to:

  1. Set the position of the element to absolute, so it uses the height of the page as reference.
  2. Set the top property to 50%, so the div element moves down to the middle of the page
  3. Use the margin-top property to move the div element a little bit above the middle of the page (if you need to).
Here’s the CSS:
.center_vert{
 position: absolute;
 top: 50%;
 margin-top: -35px;
}

See example here

How to center a div element both vertically and horizontally (dead center)

To place a div element dead center within a page, you can use the same technique as when centering it vertically and apply it to center the div element horizontally as well. To accomplish this, you need to:

  1. Set the position of the div element to absolute, so it uses the height and width of the page as reference.
  2. Set the top and left properties to 50%, so the div element moves down and to the center of the page.
  3. Use the margin-top and margin-left properties to move the div element a little bit above and left of the middle of the page (if you need to).
Here’s the CSS:
.dead_center{
 position: absolute;
 top: 50%;
 left: 50%;
 margin-top: -35px;
 margin-left: -85px;
}

See example here

And that should be it. See you next time.

Categories
Uncategorized

How to load CSS stylesheets dynamically with jQuery

Sometimes you may want to load a CSS stylesheet dynamically after your HTML page has loaded and certain conditions are met (for example, if an element with a specific class exists in the DOM). jQuery can help you accomplish that with only a few lines of code.

How to get there:

The HTML:

For this example, let’s say we need to load a stylesheet to format a div tag in the following HTML code:

<html>
<head>
<title>jQuery - Load CSS</title>
</head>
<body>
<div id="container" class="class">
<p>This is a div tag that was formatted using <a href="http://www.jquery.com" alt="Link to jQuery.com">jQuery</a>
</p></div>
</body>
</html>

The CSS:

This will be the CSS code in our sample stylesheet, “style.css”:

#container{
   border: 1px solid #000;
   background-color:#EEE;
   padding:8px;
   margin:8px;
   width: 200px;
}

The jQuery:

These are the jQuery functions we’ll use to get this done:

  • $() wrapper: as the main and most powerful jQuery function, we’ll use it to:
    • Execute code once the document has been loaded
    • Determine whether the #container div element exists in the DOM and, if true,
    • Create new HTML to link the style.css stylesheet to our page
  • append(): this jQuery function allows you to append new HTML code to any element in the DOM. For this example, we’ll attach a new <link> element to the <head> element of our document.

Bringing it all together:

With our HTML and CSS files in place, let’s get this done:

Load jQuery

  • Add the following code between the </body> and </html> tags in your HTML document (Note: your actual path might be different than the one on this example, depending on where your jquery.js file has been stored)
<script type="text/javascript" src="../jquery-1.4.2.min.js"></script>

Add the jQuery code

  • Right under the last line, add the following code:
<script type="text/javascript">

$(document).ready(function(){ //Once the document is ready, run the following code

   if($("#container").size()>0){ //Check if at least one element with the id "#container" exists within the DOM

      $("head").append($("<link rel='stylesheet' href='style.css' type='text/css' media='screen' />")); //if true, append the new <link> element to the <head> element in oor HTML page    }
});

</script>

 

 

* * * UPDATE * * *

Domenico Testa pointed out that the approach above doesn’t work correctly in IE. IE needs the  document.createStyleSheet() function to attach new stylesheet after loading the page:

document.createStyleSheet('style.css');

 

So, the final code should be:

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

	if($("#container").size()>0){
			if (document.createStyleSheet){
				document.createStyleSheet('style.css');
			}
			else {
				$("head").append($("<link rel='stylesheet' href='style.css' type='text/css' media='screen' />"));
			}
		}
	});
</script>

View example here »

 

And that should be it. This technique is useful if your page has loaded and you want to load extra CSS files when certain elements exist in the DOM. This can help you save some bandwidth and make your page load faster.