Add Description Field To Images In WordPress

When adding an image via the default WordPress image uploader, one option among many is the ability to define a description….


Interestingly enough, when embedding the image inside of a post, the description field unlike the caption field does not display by default.  Recently for a project, we needed to utilize the description field to dump in additional photo information, while the caption field was used to provide the regular text caption.

To get WordPress to display the description inside the post we had to override the the default image shortcode function WordPress used to generate the final HTML output for the images inside posts.  Then we needed to make some changes to our stylesheet and we were set. Here’s a step by step:

1. Drop this into your functions.php file…

add_shortcode('wp_caption', 'custom_img_caption_shortcode');
add_shortcode('caption', 'custom_img_caption_shortcode');

function custom_img_caption_shortcode($attr, $content = null) {

	// Allow plugins/themes to override the default caption template.
	$output = apply_filters('img_caption_shortcode', '', $attr, $content);
	if ( $output != '' )
		return $output;

	extract(shortcode_atts(array(
		'id'	=> '',
		'align'	=> 'alignnone',
		'width'	=> '',
		'caption' => ''
	), $attr));

	if ( 1 > (int) $width || empty($caption) )
		return $content;

	// Grab ID to query post_content [description] field for image
	preg_match('/([\d]+)/', $id, $matches);

	$description = '';
	if ($matches[0]) {

		global $wpdb;
		$custom_description = $wpdb->get_row("SELECT post_content FROM $wpdb->posts WHERE ID = {$matches[0]};");

		if ($custom_description->post_content) {

			$description = '<p class="wp-custom-description">'. $custom_description->post_content . '</p>';

		}
	}

	if ( $id ) $id = 'id="' . esc_attr($id) . '" ';

	return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
	. do_shortcode( $content ) . $description . '<p class="wp-caption-text">' . $caption . '</p></div>';
}

If you look at this line…

$description = '<p class="wp-custom-description">'. $custom_description->post_content . '</p>';

…you’ll notice where we dumped the description into a paragraph with a class of “wp-custom-description”. Feel free to modify the code to wrap whatever HTML around the description you need (div, span etc), in whatever location you need.

2. Edit your CSS file to style your new description…

 p.wp-custom-description { /*Some CSS Goodness Here */ } 

That’s it, you’re done! Here’s an example of the description in action….

Photo Location: North Pole

Three Penguins Discussing The Economic Stimulus Package


Posted in Tips & Tricks, Wordpress | 5 Comments

How To Get Text From Textarea using jQuery With .val() method

Recently, was doing some form validation and needed to quickly grab the text content from a textarea input using jQuery. Tried using the “.text()” method to no avail. A little hunting and found out that what I was actually looking for was the .val() method.

So for a textarea with an id of “yourTextArea”, the jQuery to assign the text content to a variable would be simple as…

 var textarea  = $('#yourTextArea').val(); 
Posted in jQuery, Tips & Tricks | 1 Comment

How To Highlight Current Category In WordPress Menu (wp_nav_menu) For Single Post Pages Using jQuery

UPDATE 10-11-2010: This information below is dated. The easiest way to accomplish this is to now just use built in classes outputted by WordPress (ie .current-post-parent). Please see this post for more information.

The new menu manager in WordPress 3.0+ is a great addition, and something that is extremely useful for clients. However in certain spots it’s not very intuitive how you get the current page/post/object highlighted.

One of those scenarios is on single post pages. By default the new menu manager will output a class of “.current-menu-item” for a category navigation link only when you are  actually navigating a category landing page, and not on single post pages assigned to that category.

I figure I could approach the solution to this in two ways. I  could try to modify the output of wp_nav_menu itself via the WordPress API or I could do it after the fact, on the client side via jQuery.

From what I’ve read regarding the first option, there actually aren’t many places to hook into this menu and thus may require the use of my own “walker class.”

Using a walker class is a new concept to me, so this probably would require a fair amount of work. Much more than I was willing to do just to highlight the current category. A far easier solution in my opinion is just to go with  the jQuery option and do this on the front-end.

So I came up with this quick solution…

1.  Link up jQuery in your WordPress header.php template, if not already there…

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

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

2. On your single post template (single.php) dump out the category name somewhere in the HTML (that later can be picked up with jQuery).

In my case I added a “title=” attribute to the #post-xx DIV.

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?> title="<?php $category = get_the_category(); echo $category[0]->cat_name; ?>">

Just to be clear, the part that I added was…

title="<?php $category = get_the_category(); echo $category[0]->cat_name; ?>

I should note, this is actually only dumping out the first category (a WordPress post can have multiple categories of course). The way I  setup sites around categories, usually there is a 1:1 relationship between posts and categories.

If you did have  multiple categories for a post, I’m not sure highlighting multiple “current categories” would be that  important to you (perhaps you’re better off leaving it how it is).  If you really do want to highlight multiple categories in the navigation, this same concept will work, but you’ll have to tweak the code a bit.

3. Use jQuery to store the category name as a variable and then apply the appropriate class in the navigation.

$(document).ready(function() {

var active_cat_name = $("body.single div.post").attr("title");

$("ul.menu li.menu-item-object-category a").filter(function(index) {
 return $(this).text() == active_cat_name; }).parent().addClass("current-menu-item");

});

Let’s look at each line separately…

var active_cat_name = $("body.single div.post").attr("title");

Here we are setting the variable “active_cat_name” equal to the assigned category name from the “title=” attribute we dumped into the HTML in step #2.

Note the use of “body.single div.post” to specifically target the appropriate DIV on single pages. Depending on how your templates are setup, the actual selector my be slightly different.

$("ul.menu li.menu-item-object-category a").filter(function(index) {
 return $(this).text() == active_cat_name; }).parent().addClass("current-menu-item");

In this line we are selecting any menu generated by wp_nav_menu (ul.menu) and scanning the anchor text for the category name. If there is a match the class of “current-menu-item” is added to the parent list item.

Note the use of “li.menu-item-object-category” in the selector which limits this to only categories in the navigation.

4. Create styles in your CSS file to highlight the current state

.current-menu-item { background-color: red; } 

And you’re done!

One quick caveat: This does a match via the “category name” because the wp_nav_menu does not output the category ID. Technically, in WordPress, it is possible to have more than one category with the same name (and different slugs). A better solution may be to use the same concept but in step 2 dump out the category slug into the HTML , and then in step 3, assuming permalinks are on, scan the anchors href instead of the anchors text for a match.

Posted in jQuery, Tips & Tricks, Wordpress | 3 Comments

How To Add Custom Styles To The WordPress Editor Dropdown

I was searching for a simple way to add my own custom classes to the WordPress 3.0 editor styles/format dropdown (Paragraph, Address, H1, H2, H3 etc etc).

Add Custom Styles To WordPress Editor Dropdown
This is a great easy way for clients who can’t / won’t go into the HTML editor to manually add predefined styles to particular elements.

After searching for a while, I couldn’t find a quick and easy way to do it, so I had to resort to the way I used to do it in previous versions of WordPress, via the TinyMCE Advanced Plugin.

This plugin adds a lot of features to the default WordPress editor, one of which of course is adding your own custom classes. (BTW, with this plugin you can also import *all* classes from your theme’s CSS file, if so desired).

This plugin technically did not support WordPress 3.0 at the time of this blog post, but I figured it was still my best option.

After I activated the plugin, I went to the TinyMCE Advanced settings page, and dropped the new “Styles” dropdown box on the editor toolbar.

Use TinyMCE Advanced To Add Styles To WordPress Dropdown Editor

*You’ll notice that this added a whole new dropdown on the toolbar. Initially I was hoping to just add my custom styles to the default “Paragraph” dropdown (which I think overall is a better experience for the user), but as mentioned, I couldn’t find a  way to do it, and decided to go with this plugin.

After placing the new “Styles” dropdown on the toolbar, populating it was actually very simple.

In the advanced section of the settings page there was this option…

In my case, I needed only to add a single class (not my entire theme’s CSS), so I left the box unchecked.

The instructions on the settings page explained how to manually add classes to the dropdown…

Custom CSS styles can be added in /wp-content/plugins/tinymce-advanced/css/tadv-mce.css. They will be imported and used in TinyMCE. Only CSS classes will be used,  also div.my-class would not work, but .my-class will.

So to add my new predefined style, I simply went to the referenced file (tadv-mce.css) and added my custom class there. I created a single “note” style…and that looked like this…

/* tadv-mce.css  */

.note {}

Now with that done, I went back into my post editor and Viola! My “note” class  had appeared in the the dropdown menu….

Add Custom Styles To WordPress Dropdown TinyMCE Populated

*You may be wondering where all those extra styles came from (wp-caption, wpGallery, wp-smiley etc etc). Those are default classes added by the plugin. Someone claimed in WP forum thread,  they can be removed by commenting out individual classes here-> wp-includes/js/tinymce/themes/advanced/skins/wp-theme/content.css , but it’s not something I have tested out..

So with the style/class is in the dropdown menu, there was  only one last thing to do. I dropped the corresponding reference in my style.css file to actually get this styled on the frontend of my site:

.note {font-size: 12px; font-style: italic; }

Also, since I was on WordPress 3.0, and thanks to a tip at this blog post, I added the same class to the editor-style.css file. (Which styled the element in the TinyMCE editor) and I was all done!

Posted in Tips & Tricks, Wordpress | 13 Comments

How To Get Top Parent Page ID In WordPress

Often when working with pages in WordPress you’ll need to get the ID of the very top parent in a hierarchy of pages. This could be useful for many reasons, but I run into the need most often when I need to list out multiple levels of children pages on the sidebar for a given section of pages.

When you are on a parent page life is easy because listing its children pages on a sidebar is simple as this:

<ul>
<?php  wp_list_pages("child_of={$post->ID}&title_li=");  ?>
</ul>

*In this case “child_of={$post->ID}” simply means get all children pages of the current page.

Now that’s great, but when you navigate to one of those child pages, or even worse a third-level child page, you’ll quickly realize that “$post->ID”, no longer refers to the very top parent, but to the page you are on and therefore the function doesn’t work as intended.

The solution is actually pretty simple. Instead of using the current page ID as a parameter in wp_list_pages(), you simply create a new function to always return the very top parent page ID and use that.

Here’s a very simple function that will accomplish that. Drop this in your functions.php file..

function get_top_parent_page_id() {

    global $post;

    // Check if page is a child page (any level)
    if ($post->ancestors) {

        //  Grab the ID of top-level page from the tree
        return end($post->ancestors);

    } else {

        // Page is the top level, so use  it's own id
        return $post->ID;

    }

}

And then update your code in your template to look like this…

<?php $parent_page = get_top_parent_page_id($post->ID); ?>

<ul>
<?php wp_list_pages("child_of=$parent_page&title_li="); ?>
</ul>
Posted in Tips & Tricks, Wordpress | 8 Comments

Easy Breadcrumbs In WordPress

When creating the page section of a client site in WordPress, the need for breadcrumb navigation often arises.  There are probably multiple methods/plugins that can do this, but the one I use is “Fold Page List“.

Fold Page List, is a plugin that primarily adds some enhanced functionality to the wp_list_pages() function, but a neat side feature is that is also creates a new function called wswwpx_page_breadcrumbs() which lets you very easily create breadcrumb navigation.

The parameters for the function are really quite simple. After the plugin is installed, the function should be used as follows…

wswwpx_page_breadcrumbs($homelink, $separator, $echo);

And the default values are as follows…

  • $homelink: array(’label’=>’Home’, ‘title’=>’Homepage’, ‘link’=>’/’)
  • $separator: string(’&nbsp;&raquo;&nbsp;’)
  • $echo: boolean (true)

So an example of how to use this….

<?php

$homepage_url = get_bloginfo('url');

wswwpx_page_breadcrumbs(array('label'=>'Home', 'title'=>'Homepage',
'link'=>"$homepage_url")); 

?>

And that outputs a breadcrumb (using default values for $separator) in the format of…

Home » Page » Subpage

Cool! To download the plugin and see full information please visit the author’s page here .

Posted in Tips & Tricks | Leave a comment

Check If Current Page Has Any Subpages in WordPress

Really thought there would be a built-in function in WordPress to check for the existence of  any subpages while on a parent page, but apparently not.

So here’s a quick dirty little function that will do just that. Drop this in your functions.php file…

function has_subpage (){

global $post;
$pages = get_pages("sort_column=menu_order&amp;child_of={$post->;ID}");
if ($pages) return TRUE;

}

And then you can use the function as such…

if (is_page() &amp;&amp; has_subpage()) {

/* Do something special to pages that have children */

}
Posted in Tips & Tricks | 2 Comments

Return The Post ID and Modify A Specific Entry Inside a WordPress Loop

I recently needed to slightly modify the output for a specific entry inside a category loop on a client’s WordPress install. Having a terrible memory, I seem to always forget functions for basic things like this, and this case was no exception.

A few keystrokes in Google, and I was quickly reminded that WordPress does in fact have a built in function that returns the ID inside the loop –> get_the_ID

And using it is simple as…

<?php

$id = get_the_ID();
if($id == 2817): ?>

 /* Do Something Special Here */

<?php endif; ?>;

*There is also the_ID() which *displays* the ID inside the loop, but that’s not what I was after, since I needed to run a conditional check for a specific post

I also was reminded that if I didn’t want to use the WordPress built-in function, I could just grab the ID from the global $post object. So this conditional works as well…

<?php if($post->ID == 2817): ?>

*Depending on how/where you do it, you may have to declare the $post variable as global before this works. Example:

<?php

global $post;
if($post->ID == 2817): ?>

 /* Do Something Special Here */

<?php endif; ?>

You may be wondering why you would ever need to modify the output for a specific post that’s moving through the loop and I agree, this is not something you’ll probably have to do very often.

But imagine a situation where you are using the WordPress post/category paradigm in an abnormal fashion…for example, a list of people/profiles sorted by name and not date. (I’ve done this many times on client sites).

Perhaps there is one person..maybe the CEO who needs a little extra spizazz on his entry in the category loop (perhaps different/more custom fields, additional images etc etc).

Using this conditional allows me to modify the template for his specific entry very quickly without too much fuss.

Also, I should point out, if what you want to do is purely visual (as opposed to modifying the actual HTML output as I needed to do) you’re much better of using some plain ol’ CSS.

By default every entry in the loop should have a custom #id attached to it in the html. So, for a specific entry, if you just need to just change colors, change size, add borders, emphasize text etc etc….probably best to do that in your CSS file without even touching PHP to add extra markup.

#post-2817 { border: 2px solid black; }
Posted in Tips & Tricks | Leave a comment

Where’s The Index Page (Or Archive Page) for Custom Post Types In WordPress 3.0?

WordPress is probably my goto CMS platform (yes I said CMS) for client work in my day-to-day gig (full-time web designer/developer). Needless to say, since I use it so much, I’m stoked that the feature-packed WordPress 3.0 is upon us.

Unfortunately, I’ve been so busy that up until recently I haven’t been able to really follow along the nightly build/beta releases, but I have been salivating for custom post types for a long, long time. So much so, that I’ve used Expression Engine (with far better implementation of custom posts/custom fields) quite a bit as an alternative for clients.

Alas WordPress 3.0 is right around the corner and I’ve toyed around with the vaunted custom post type feature a bit, and although not nearly as polished as the Expression Engine implementation, it is a very powerful step forward for the WordPress platform. Aside from the fact that there’s no real admin UI as of yet (*cough* Expression Engine *cough*) the first thing that really raised an eyebrow was figuring out where exactly to put these new, peculiar post types.

It was apparent after scouring a few blogs, that once setting up the custom post type in the functions.php file, that I could modify any loop by simply adding a parameter to the WP Query ie…

global $wp_query;

$wp_query = new WP_Query("post_type=your_post_type&amp;posts_per_page=5");

Cool…easy peasey…

BUT…what wasn’t apparent was how to create a landing page just for a specific post type, one that was accessible by a unique URL (ie yourblog.com/your_post_type).

Before the big jump to WordPress 3.0 I would use categories primarily for the major sections of the clients’ sites, and of course WP has always had an easy to understand template hierarchy that lets you create unique templates for different categories, and lets those categories become accessible by very pretty permalinks, if so desired.

I really didn’t see anything in the currently sparse 3.0 documentation that explained how to do something similar for custom post types. Hmm…

So I did a little more scouring and I found out that I’m not the only one who found this implementation (or should I say “lack of implementation”) a little confusing.  Over on Justin Tadlock’s blog, I found someone raise similar concerns, and Justin’s response to it. http://justintadlock.com/archives/2010/04/29/custom-post-types-in-wordpress#comment-188177

Interestingly enough, not only did that someone find the custom post type implementation lacking…they actually wrote a helper class to try and make up for it. (Wow…I was just content with complaining about it…so kudos to him). To learn more about that helper class see: Smarter Custom Post Types in WordPress 3.0

Going back to the original discussion at Justin Tadlock’s blog, the alternative solution suggested by Justin himself, was to drop the modified custom post type loop on a custom page template. This actually was the way I started doing it initially, but it felt a little hackish for such an acclaimed new feature. (But apparently since there isn’t an unhackish way of doing it yet, I’m adopting this method for the time being.)

Also interestingly, there’s some debate as to whether pagination and site feeds will work on this new  “custom post type on a custom page template landing page” (that’s a mouthful). Honestly I haven’t dug into it to much yet, but I’ll be sure to update this post if and when I find out more about that.

My take away from this…the custom post types in WordPress 3.0, although great, are still a work in progress.

UPDATE: I’ve found a couple more solutions both of which seem to take the basic concept of creating your own archive/landing template for a post-type and making the URL map to the correct place through hacking/modifying of  WP’s rewrite rules. Here is a cool write up about it from Ballyhoo Blog ,  and another post from kovshenin.com where the author briefly hints at using the “$wp_rewrite->add_permastruct()” method to achieve the desired effect.

Posted in Tips & Tricks | 2 Comments