Archive

Posts Tagged ‘custom taxonomy’

WordPress as a Knowledge Base

May 9th, 2012 Comments off

At work we previously used KBPublisher to manage our knowledge base. It costed money, it was hard to style, code is encrypted with ion cube and so on, basically very hard to maintain. WordPress can do the same things and even better.

This tutorial will show you how to use custom taxonomies for knowledge base sections and custom posts for knowledge base articles.


Step 1 Administration

Knowledge base sections and articles need to be managed. WordPress makes this easy to do with custom taxonomies and custom post types.

Just register the new taxonomy and post type. Add the following into functions.php from your theme.

For more information on the ins and outs of this functionality, read our other custom post type and custom taxonomy articles.

function register_kb() 
	register_post_type( 'knowledgebase',
		array(
			'labels' => array(
				'name' => 'Knowledge Base',
				'menu_name' => 'Knowledge Base',
				'singular_name' => 'Article',
				'all_items' => 'All Articles'
			),
			'public' => true,
			'publicly_queryable' => true,
			'show_ui' => true,
			'show_in_menu' => true,
			'show_in_nav_menus' => true,
			'menu_position ' => 20,
			'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'post-formats', 'revisions' ),
			'hierarchical' => false,
			'taxonomies' => array( 'section' ),
			'has_archive' => true,
			'rewrite' => array( 'slug' => 'knowledgebase', 'hierarchical' => true, 'with_front' => false )
		)
	);

	register_taxonomy( 'section', array( 'knowledgebase' ),
		array(
			'labels' => array(
				'name' => 'Sections',
				'menu_name' => 'Sections',
				'singular_name' => 'Section',
				'all_items' => 'All Sections'
			),
			'public' => true,
			'hierarchical' => true,
			'show_ui' => true,
			'rewrite' => array( 'slug' => 'knowledgebase-section', 'hierarchical' => true, 'with_front' => false ),
		)
	);

add_action( 'init', 'register_kb' );

function kb_rewrite_rules( $wp_rewrite ) 
	$new_rules = array( 'knowledgebase/(.*)/(.*)' => 'index.php?post_type=knowledgebase&section=' . $wp_rewrite->preg_index( 1 ) . '&knowledgebase=' . $wp_rewrite->preg_index( 2 ) );
	$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;

add_action( 'generate_rewrite_rules', 'kb_rewrite_rules' );

This will run after WordPress has finished loading but before any headers are sent, registering the post type and taxonomy. Also, it will add the rewrite rules for the permalinks of the taxonomy and post type.

The register_post_type registers the custom post type, this is used for the KB articles. The register_taxonomy registers the custom taxonomy, this is used for the KB sections. The articles won’t be hierarchical but the sections will be, so it gives the possibility to create a tree structure.

Also it would be nice to show the sections that an article is assigned to.

function kb_columns( $defaults ) 
	$defaults['section'] = 'Sections';
	return $defaults;

add_filter( 'manage_knowledgebase_posts_columns', 'kb_columns' );

function kb_custom_column( $column_name, $post_id ) 
	$taxonomy = $column_name;
	$post_type = get_post_type( $post_id );
	$terms = get_the_terms( $post_id, $taxonomy );
	if ( !empty( $terms ) ) 
		foreach ( $terms as $term ) 
			$post_terms[] = " " . esc_html(sanitize_term_field('name', $term->name, $term->term_id, $taxonomy, 'edit')) . '';
		}
		echo join( ', ', $post_terms );
	}
	else echo 'No terms.';
}
add_action( 'manage_knowledgebase_posts_custom_column', 'kb_custom_column', 10, 2 );

Now add some sections and some articles so there is something to show.


Step 2 Showing the Sections

Add the following into functions.php from your theme.

function kb_sections( $sections = array(), $active_section = null ) 
	$taxonomy = 'section';
	$link_class = '';
	if ( empty( $sections ) ) 
		$link_class = 'root';
		$sections = get_terms( $taxonomy, array( 'parent' => 0, 'hide_empty' => 0 ) );
		$active_section = kb_active_section();
		echo '
    '; if ( empty( $active_section ) ) $active_section = ''; foreach ( $sections as $section ) $toggle = ''; $section_children = get_terms( $taxonomy, array( 'parent' => $section->term_id, 'hide_empty' => 0 ) ); if ( !empty( $section_children ) && $link_class != 'root' ) $toggle = ''; echo '
  • '; echo '' . $toggle . $section->name . ''; if ( !empty( $section_children ) ) echo '
      '; kb_sections( $section_children, $active_section ); echo ""; } echo "
    "; } function kb_active_section() $taxonomy = 'section'; $current_section = ''; if ( is_single() ) $sections = explode( '/', get_query_var( $taxonomy ) ); $section_slug = end( $sections ); if ( $section_slug != '' ) $term = get_term_by( 'slug', $section_slug, $taxonomy ); else $terms = wp_get_post_terms( get_the_ID(), $taxonomy ); $term = $terms[0]; $current_section = $term->term_id; } else $term = get_term_by( 'slug', get_query_var( $taxonomy ), get_query_var( 'taxonomy' ) ); $current_section = $term->term_id; return $current_section; }

In the theme folder create a file called sidebar-sections.php where your kb_sections function will be called outputting an unordered and nested list of sections.


Like this, the KB sections can be shown everywhere as desired by including the sidebar.



Step 3 Showing the Articles

Add the following into functions.php from your theme.

function kb_article_permalink( $article_id, $section_id ) 
	$taxonomy = 'section';
	$article = get_post( $article_id );
	$section = get_term( $section_id, $taxonomy );
	$section_ancestors = get_ancestors( $section->term_id, $taxonomy );
	krsort( $section_ancestors );
	$permalink = '' . $article->post_title . '';
	return $permalink;

Note: this method is necessary because an article can be linked to multiple sections.

This will generate a hierarchical permalink structure.

Like: /knowledgebase/section-slug/sub-section-slug/another-sub-section-slug/article-slug

In the theme folder then create these files: archive-knowledgebase.php, single-knowledgebase.php, content-knowledgebase.php, taxonomy-section.php.

In archive-knowledgebase.php add the following to show the sections and recent articles.

ID, 'section' );
	$term = $terms[0];
	echo kb_article_permalink( $post->ID, $term->term_id );
endwhile;
get_footer();
?>

In single-knowledgebase.php add the following.


In content-knowledgebase.php add the following.


In taxonomy-section.php add the following to show a list of articles from a section.

query, array( 'posts_per_page' => 100 ) );
query_posts( $args );
$term = get_term_by( 'slug', get_query_var( 'term' ), 'section' );

get_header();
get_sidebar( 'sections' );
while ( have_posts() ) : the_post();
	echo kb_article_permalink( $post->ID, $term->term_id );
endwhile;
get_footer();
?>

This can be structured and styled as desired.


Example

A real life example of how this works and how it can be used: syneto.net


References

Original from: http://wp.tutsplus.com/tutorials/business/wordpress-as-a-knowledge-base/

Add a Custom Column in Posts and Custom Post Types Admin Screen

March 23rd, 2012 Comments off

In this tutorial we will see how to add a new column to the WordPress Posts management screen and in this column we will show the Featured Image of each Post. This new column will also be added in the management screen of any active Custom Post Type.


Step 1 Activate Featured Images

In this tutorial we will use the functions.php file available in our active theme directory. If the file is not present, you can create a new one with the following contents:


First of all, check if the Featured Image is available on the Add New Post page:

If you don’t see the Featured Image box, add this line to functions.php:

add_theme_support('post-thumbnails');

We also set a custom size of 55 pixels that will be used to show the featured image’s preview:

add_image_size('featured_preview', 55, 55, true);

Step 2 Add Custom Column to the Posts Screen

Now we’ll add a new column in the Posts list table that will contain the featured image of each Post. But first, we need a function to get the featured image of a Post: ST4_get_featured_image.

Open the functions.php file in your theme directory and paste this:

// GET FEATURED IMAGE
function ST4_get_featured_image($post_ID) 
	$post_thumbnail_id = get_post_thumbnail_id($post_ID);
	if ($post_thumbnail_id) 
		$post_thumbnail_img = wp_get_attachment_image_src($post_thumbnail_id, 'featured_preview');
		return $post_thumbnail_img[0];
	
}

And we define two functions: the first will add the new column, the second will call and show the featured image in every cell of the new column:

// ADD NEW COLUMN
function ST4_columns_head($defaults) 
	$defaults['featured_image'] = 'Featured Image';
	return $defaults;


// SHOW THE FEATURED IMAGE
function ST4_columns_content($column_name, $post_ID) 
	if ($column_name == 'featured_image') 
		$post_featured_image = ST4_get_featured_image($post_ID);
		if ($post_featured_image) 
			echo '';
		
	}
}

These two functions will be “hooked” into the WordPress core function that creates the Posts table.

About WordPress Hooks

Developers can modify WordPress default behavior through the WordPress APIs:

Hooks are provided by WordPress to allow your plugin to ‘hook into’ the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion.

In short, Hooks allow developers to extend WordPress features without editing core files. There are two types of Hooks: Actions and Filters. Both are launched during WordPress execution, but while Filters accept, transform and return an input, Actions return nothing, though can print everything you need.

In our case, the ST4_columns_head function takes the $defaults array that contains the default Posts table columns (Title, Category, Tags and so on…), adds a new featured_image item to the array and returns it to the core function that WordPress uses to print the table html.

On the contrary, the ST4_columns_content function accepts two variables ($column_name and $post_ID), and – depending on them – prints an output. To be more precise, ST4_columns_content is invoked on each iteration of the loop that traverses the $defaults array. On each iteration, WordPress passes two arguments to our function: the column name and the post ID. The function analyzes all column names and when the name is equal to the one we specified in ST4_columns_head, checks for featured image.

So, now we can hook our functions to WordPress plugin APIs:

add_filter('manage_posts_columns', 'ST4_columns_head');
add_action('manage_posts_custom_column', 'ST4_columns_content', 10, 2);

The 10 and 2 parameters are respectively: the order (priority) in which the function will be executed, and the number of arguments that the function accepts. Anyway, you can read more in the WordPress Codex under add_action.


Final Result

Now we can finally write a Post with a Featured Image:

So, when you open the manage Posts screen in /wp-admin/edit.php, you’ll see the new Featured Image column:

First two posts have the featured image, the third (a post without a featured image) does not, so nothing is displayed.

To show a default image for posts that don’t have a featured image, you can modify the ST4_columns_content function this way:

';
		
		else 
			// NO FEATURED IMAGE, SHOW THE DEFAULT ONE
			echo '';
		
	}
}
?>

The default.jpg image must be present in the images directory of our active theme.

You can also show / hide this new column by opening the Screen Options panel and clicking the Featured Image checkbox:


Step 3 Add the Featured Image Column to Custom Post Types

One of the most interesting and useful features of WordPress, is the possibility to add Custom Post Types (and also Custom Taxonomies). You can use post types to create new kinds of content, different from Posts and Pages, for example to manage a Movie database. In fact, when you add a custom post type, WordPress creates all the management pages for that post type: you can add, edit and delete those posts in the same way as default Posts and Pages.

Now we create a new Custom Post Type: Movies, through the WordPress register_post_type function:

add_action('init', 'ST4_add_movies');  

function ST4_add_movies() 
	$args = array(
		'label' => __('Movies'),
		'singular_label' => __('Movie'),
		'public' => true,
		'show_ui' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'rewrite' => true,
		'supports' => array('title', 'editor', 'thumbnail')
	);
	register_post_type( 'movie' , $args );

So, when you add a featured image to a Movie post…

… you will see the featured image also in the manage Movies screen (note that also here you can show / hide the column in the Screen Options):


Other Usages

Adding the Custom Column Depending on Post Type

If you use the manage_posts_columns and manage_posts_custom_column hooks, the column will be shown in all manage posts screens. These filters in fact will work for posts of all types except Pages.

// ALL POST TYPES: posts AND custom post types
add_filter('manage_posts_columns', 'ST4_columns_head');
add_action('manage_posts_custom_column', 'ST4_columns_content', 10, 2);

If you want to add a column only in the manage Posts screen use:

// ONLY WORDPRESS DEFAULT POSTS
add_filter('manage_post_posts_columns', 'ST4_columns_head', 10);
add_action('manage_post_posts_custom_column', 'ST4_columns_content', 10, 2);

If you want to add a column only in the manage Pages screen use:

// ONLY WORDPRESS DEFAULT PAGES
add_filter('manage_page_posts_columns', 'ST4_columns_head', 10);
add_action('manage_page_posts_custom_column', 'ST4_columns_content', 10, 2);

If you want to add a column only in the manage Movies screen use:

// ONLY MOVIE CUSTOM TYPE POSTS
add_filter('manage_movie_posts_columns', 'ST4_columns_head_only_movies', 10);
add_action('manage_movie_posts_custom_column', 'ST4_columns_content_only_movies', 10, 2);

// CREATE TWO FUNCTIONS TO HANDLE THE COLUMN
function ST4_columns_head_only_movies($defaults) 
	$defaults['directors_name'] = 'Director';
	return $defaults;

function ST4_columns_content_only_movies($column_name, $post_ID) 
	if ($column_name == 'directors_name') 
		// show content of 'directors_name' column
	
}

Add the Custom Column to Another Post Type

If you have other Custom Post Types, you can easily add the featured image column to them.
If you added the post type manually, check the file where the custom post is added and look for the first argument of the register_post_type function:

register_post_type( 'book' , $args ); // book is the post type

If the custom post type is defined through another plugin and/or you can’t find where the register_post_type is, open the Custom Post management screen in your browser and check the URL:


http://www.yoursite.com/wp-admin/edit.php?post_type=book

In this case, book is the post type.

Finally, modify the hooks this way, replacing movie with book:

add_filter('manage_book_posts_columns', 'ST4_columns_book_head');
add_action('manage_book_posts_custom_column', 'ST4_columns_book_content', 10, 2);

Don’t forget to create two functions: ST4_columns_book_head to create the column, and ST4_columns_book_content to display the content.

Add Two Custom Columns

If you need to add more than one column, you can easily do this:

// ADD TWO NEW COLUMNS
function ST4_columns_head($defaults) 
	$defaults['first_column']  = 'First Column';
	$defaults['second_column'] = 'Second Column';
	return $defaults;


function ST4_columns_content($column_name, $post_ID) 
	if ($column_name == 'first_column') 
		// First column
	
	if ($column_name == 'second_column') 
		// Second column
	
}

Remove Default Columns

You can also remove a WordPress default column, for example the Category column in the Posts management screen:

add_filter('manage_post_posts_columns', 'ST4_columns_remove_category');

// REMOVE DEFAULT CATEGORY COLUMN
function ST4_columns_remove_category($defaults) 
	// to get defaults column names:
	// print_r($defaults);
	unset($defaults['categories']);
	return $defaults;


References

Original from: http://wp.tutsplus.com/tutorials/creative-coding/add-a-custom-column-in-posts-and-custom-post-types-admin-screen/

Creating a Filterable Portfolio with WordPress and jQuery

February 6th, 2012 Comments off

Learn in this tutorial how to make a filterable Portfolio with jQuery integrated with WordPress, remember that this portfolio kind can make a big difference on your themes!


Step 1: Introduction

You can use the code from this tutorial in any theme that you’ve created or are creating, we’ll follow simple steps and in my case, I’ll use the default Twenty Eleven theme and running on WordPress 3.3. Okay, let’s work!

You can use the code used in this tutorial in any theme that you’ve created or are creating.


Step 2: Creating the Project Item on Admin

We’ll need to create a section on Admin bar called Project, in this section you’ll create all the portfolio entries with their respective thumbnail and demo link.

Open the functions.php file and at the end, let’s create a function to register the Project item. (You can see the complete function at the end of this step)

add_action('init', 'project_custom_init');    

/* SECTION - project_custom_init */
function project_custom_init()

	// the remainder code goes here

/* #end SECTION - project_custom_init --*/

In this code we are using the add_action function so that when WordPress begins to load our function will be called.

Inside the project_custom_init function lets add the code that registers a Custom Post Type called Project.


	// The following is all the names, in our tutorial, we use "Project"
	$labels = array(
		'name' => _x('Projects', 'post type general name'),
		'singular_name' => _x('Project', 'post type singular name'),
		'add_new' => _x('Add New', 'project'),
		'add_new_item' => __('Add New Project'),
		'edit_item' => __('Edit Project'),
		'new_item' => __('New Project'),
		'view_item' => __('View Project'),
		'search_items' => __('Search Projects'),
		'not_found' =>  __('No projects found'),
		'not_found_in_trash' => __('No projects found in Trash'),
		'parent_item_colon' => '',
		'menu_name' => 'Portfolio'
	);

	// Some arguments and in the last line 'supports', we say to WordPress what features are supported on the Project post type
	$args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'has_archive' => true,
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title','editor','author','thumbnail','excerpt','comments')
	);

	// We call this function to register the custom post type
	register_post_type('project',$args);

The code above will add an item on the Admin menu called Portfolio and it will be in this section that we’ll create all the portfolio items.

Now, inside the function, let’s add more code.

	// Initialize Taxonomy Labels
	$labels = array(
		'name' => _x( 'Tags', 'taxonomy general name' ),
		'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search Types' ),
		'all_items' => __( 'All Tags' ),
		'parent_item' => __( 'Parent Tag' ),
		'parent_item_colon' => __( 'Parent Tag:' ),
		'edit_item' => __( 'Edit Tags' ),
		'update_item' => __( 'Update Tag' ),
		'add_new_item' => __( 'Add New Tag' ),
		'new_item_name' => __( 'New Tag Name' ),
	);

	// Register Custom Taxonomy
	register_taxonomy('tagportfolio',array('project'), array(
		'hierarchical' => true, // define whether to use a system like tags or categories
		'labels' => $labels,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'tag-portfolio' ),
	));

Attention to the ‘hierarchical’ argument on the register_taxonomy function, if you type true you will have a system like categories for your portfolio items, but if you type false you will have a system like tags. I prefer the category style system.

Oh yeah! The project_custom_init() function is finished! See below for the full code of this function.

	add_action('init', 'project_custom_init');  

	/*-- Custom Post Init Begin --*/
	function project_custom_init()
	
	  $labels = array(
		'name' => _x('Projects', 'post type general name'),
		'singular_name' => _x('Project', 'post type singular name'),
		'add_new' => _x('Add New', 'project'),
		'add_new_item' => __('Add New Project'),
		'edit_item' => __('Edit Project'),
		'new_item' => __('New Project'),
		'view_item' => __('View Project'),
		'search_items' => __('Search Projects'),
		'not_found' =>  __('No projects found'),
		'not_found_in_trash' => __('No projects found in Trash'),
		'parent_item_colon' => '',
		'menu_name' => 'Project'

	  );

	 $args = array(
		'labels' => $labels,
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'has_archive' => true,
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array('title','editor','author','thumbnail','excerpt','comments')
	  );
	  // The following is the main step where we register the post.
	  register_post_type('project',$args);

	  // Initialize New Taxonomy Labels
	  $labels = array(
		'name' => _x( 'Tags', 'taxonomy general name' ),
		'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search Types' ),
		'all_items' => __( 'All Tags' ),
		'parent_item' => __( 'Parent Tag' ),
		'parent_item_colon' => __( 'Parent Tag:' ),
		'edit_item' => __( 'Edit Tags' ),
		'update_item' => __( 'Update Tag' ),
		'add_new_item' => __( 'Add New Tag' ),
		'new_item_name' => __( 'New Tag Name' ),
	  );
		// Custom taxonomy for Project Tags
		register_taxonomy('tagportfolio',array('project'), array(
		'hierarchical' => true,
		'labels' => $labels,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'tag-portfolio' ),
	  ));

	
	/*-- Custom Post Init Ends --*/

If you go to the Admin now, you will see a new item on menu called Portfolio like the image below:

Let’s create a new function that will ensure nice messages are shown when the user, for example, creates a new item on portfolio or something like this.

The code below must be typed below our last function and not inside it.

	/*--- Custom Messages - project_updated_messages ---*/
	add_filter('post_updated_messages', 'project_updated_messages');

	function project_updated_messages( $messages ) 
	  global $post, $post_ID;

	  $messages['project'] = array(
		0 => '', // Unused. Messages start at index 1.
		1 => sprintf( __('Project updated. View project'), esc_url( get_permalink($post_ID) ) ),
		2 => __('Custom field updated.'),
		3 => __('Custom field deleted.'),
		4 => __('Project updated.'),
		/* translators: %s: date and time of the revision */
		5 => isset($_GET['revision']) ? sprintf( __('Project restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
		6 => sprintf( __('Project published. View project'), esc_url( get_permalink($post_ID) ) ),
		7 => __('Project saved.'),
		8 => sprintf( __('Project submitted. Preview project'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
		9 => sprintf( __('Project scheduled for: %1$s. Preview project'),
		  // translators: Publish box date format, see http://php.net/date
		  date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
		10 => sprintf( __('Project draft updated. Preview project'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
	  );

	  return $messages;
	

	/*--- #end SECTION - project_updated_messages ---*/

This function creates custom messages for when a user modifies the portfolio post, see a message example on image below:

You can see that with only this code you can add tags/categories to your portfolio and create new portfolio items! But let’s add more one feature, good idea? Sure!

Adding a Demo URL Meta Box

In this step, we’ll add a meta box on the portfolio item creation screen where the user can paste a url to the website or other page.

Let’s create three functions to add this meta box where we will save our URL for the portfolio item. The code goes below the last function that we’ve created.

	/*--- Demo URL meta box ---*/

	add_action('admin_init','portfolio_meta_init');

	function portfolio_meta_init()
	
		// add a meta box for WordPress 'project' type
		add_meta_box('portfolio_meta', 'Project Infos', 'portfolio_meta_setup', 'project', 'side', 'low');

		// add a callback function to save any data a user enters in
		add_action('save_post','portfolio_meta_save');
	

	function portfolio_meta_setup()
	
		global $post;

		?>
			

'; function portfolio_meta_save($post_id) // check nonce if (!isset($_POST['meta_noncename']) // check capabilities if ('post' == $_POST['post_type']) if (!current_user_can('edit_post', $post_id)) return $post_id; } elseif (!current_user_can('edit_page', $post_id)) return $post_id; // exit on autosave if (defined('DOING_AUTOSAVE') == DOING_AUTOSAVE) return $post_id; if(isset($_POST['_url'])) update_post_meta($post_id, '_url', $_POST['_url']); else delete_post_meta($post_id, '_url'); } /*--- #end Demo URL meta box ---*/

I won’t explain in details this code because you can learn about meta boxes in this tutorial: Reusable Custom Meta Boxes or just do a little search through the WordPress Codex or on Google.

The code above just creates one meta box with one field where the user can type a URL. We need all these functions, the first just initializes the meta box, the second is the meta box code, and the last is a function to save the data.

Ok! After this, we can go on to next step and work on the front-end, because the back-end is done! We’ll then add the content after.


Step 3: Creating the Portfolio Page template

Now we’ll work to show our portfolio entries to the user! But first let’s create some categories and then add some items to the portfolio.

In this tutorial I’ll use a two column portfolio layout, with some adjustments on markup and CSS you can create a lots of layouts!

A few tips to create a portfolio item

  • Create the tags/categories first
  • In the “Add New Project” page you’ll have an editor like the post/page editor, then just type all the text and images that your user will see when they click on the “More Details” link
  • To add thumbnails we’ll use the Featured Image that is a default WordPress feature
  • In this tutorial I’ll use images with 400px x 160px (width and height), but feel free to use one that you like and that fits in your layout
  • Use http:// before the links on the meta box so you don’t get a 404 not found error

Ok, the first thing that we’ll need to do now is create a new Page Template called “Portfolio 2 Columns”, so let’s go!

Creating the Page Template

First, duplicate the page.php file. Then, rename it to page_portfolio_2c.php.

We need to edit this new file and paste the code below on the file’s first line:


This will show a new option on the page creation screen, but remember that this code MUST be pasted on the file’s first line!

Now just erase all the content inside content div, in this tutorial, I’m using the Twenty Eleven theme and after erasing, I have this code in my file:





		

If you are using your own theme, then erase all the lines that get content from your page, like the_content() for example. We’ll create some custom code, so don’t leave other code here, in the portfolio page we just need your projects!

Now, go to WordPress Admin and create a new Page called “Portfolio” and don’t forget to select “Portfolio 2 Columns” in the Template field, like the image below.

Just add a title and leave the content blank, we don’t need it.

If you try to access the page now you’ll get only the header, footer and blank content. So, let’s add life to our filterable portfolio!


Step 4:The jQuery Filterable Portfolio

Let’s talk a little about the plugin that we’ll use to make the portfolio.

The plugin

In this tutorial I’ll make use of a plugin called Filterable, this plugin was created by GetHifi.

This plugin was written without jQuery’s compatibility mode, so I just changed it and the version that works fine with WordPress is in the Source Code file for this tutorial.

The plugin is a little old, to be more exact, it’s from 2009, but it’s on MIT License, so you can use on premium themes, commercial sites and wherever you like.

Just download the modified script that is on Source Code (link on tutorial top) and let’s begin! If you like, visit the homepage to get more details about it.

How Filterable works

Using Filterable is very simple! The first step is use the right markup, the plugin expects markup like the example below:

	

Here we have the filter items, when we click on one of these links, then all the magic will happen. Important: all the entries will need a class with the same text in the ‘href’ and ‘rel’ attributes.

And now, we have the portfolio items markup:

	

Important: What really matters here is that all the items (li) must be inside a (ul), in other words, must be wrapped. Note that we use a div too, we use it because we’ll ‘float’ the li elements, so it is important to have another wrapper and a clear div to avoid structure breaking problems.

After this, we’ll need to call the filterable script in our functions.php file and initialize the filterable portfolio by calling the filterable() function, like the code below:

	

But for now, we’ll add our custom markup inside the li, but, we’ll need to generate all the filters and class names with PHP to get all the categories, portfolio entries and all the other details from WordPress! Let’s work!

Creating the Portfolio Filter

Let’s back to the page_portfolio_2c.php file and write the portfolio filter. The code actually is something like the code below:





		

We need get all the terms/categories from WordPress, edit some names to use inside the class attribute and print a ul for the required template.

We’ll type the following code inside the #content div:

	';
		echo '
  • All
  • '; if ( $count > 0 ) foreach ( $terms as $term ) $termname = strtolower($term->name); $termname = str_replace(' ', '-', $termname); echo '
  • '.$term->name.'
  • '; } echo ""; ?>

    The code above will generate a ul with the default element ‘All’, and do a loop on terms to print all other categories that have entries. Let’s do a more detailed explanation:

    First, we create a variable called $terms, and we use the get_terms() function that returns an array with all terms. As a parameter, the function requires a string or an array of strings with the taxonomy name(s), we pass tagportfolio, that was the name we used in our functions.php file. You can get more detailed info under get_terms() in the WordPress Codex.

    Then, we create a variable called $count and use the count() function to get the total number of elements in the array, we print the default markup and the All item.

    After that, we verify if the $count variable is greater than zero, if yes, we have at least one category with items to print.

    Inside if, we create a foreach loop to get all array values, and create a different li element for each element in the $terms array.

    Inside foreach, we create a variable called $termname to store the term name, remember that we change the text to lower case, because this variable will be used inside the class attribute.
    Then, we just replace any white space with a - using the str_replace function, this line will enable you to use categories/terms with more than one word, like “WordPress Themes” for example.
    And last, we print an li element and use our variables to print the data in the right place.

    If you test now, you’ll see a categories/terms list with the names that you created in WordPress Admin. Now, let’s work on the items.

    Displaying the Portfolio Items

    Now let’s display the portfolio items, we need do it following the required template shown above.

    We’ll do it just adding the code below:

    
     'project', 'posts_per_page' => -1));
    	$count =0;
    ?>
    
    
      have_posts() ) : $loop->the_post(); ?> ID, 'tagportfolio' ); if ( $terms && ! is_wp_error( $terms ) ) : $links = array(); foreach ( $terms as $term ) $links[] = $term->name; $links = str_replace(' ', '-', $links); $tax = join( " ", $links ); else : $tax = ''; endif; ?>
    • Sorry, no portfolio entries found.

    A lot of lines of code, no? But don’t worry, I’ll explain the code for you.

    The first step is create a custom query, we do it with WP_Query function, I pass as parameter the custom post type “project”, that we created on functions.php file. This query will get all the projects that you’ve created.

    Then, I do a loop like we do normally with post exhibition, for example.

    Inside the while, we do the same process used on filter creation, but here we create a array called links where we’ll store all the terms of the post. Note that now, beyond the taxonomy name we pass the post ID in get_the_terms().

    Then, we use join and create a unique string with all array elements, if the post terms are “WordPress” and “Design”, the $tax variable will be equal to “wordpress design”, we’ll use this to add the right classes to allow the portfolio to be filterable.
    If the post doesn’t have terms, we just set $tax being equal to a blank string.

    After this, we create a variable called $infos where we’ll get the demo url from our Custom Post Field created in the functions.php file

    Then, we just print the template markup and make use of functions like get_the_excerpt(), the_post_thumbnail (note that you can change the dimensions to fit your layout, if you for example, would like to create a three column portfolio.)

    If you update the page, you will see all the items listed, but the filter still doesn’t work. Let’s fix it!

    Using Filterable in WordPress

    Now, let’s use our plugin. Did you already download it? If yes, copy and paste the filterable.js file inside the js/ folder.

    In the functions.php file, let’s add the jQuery library to the ‘head’ tag first. To do it we’ll use a custom function and the wp_enqueue_script function.

    	function enqueue_filterable()
    	
    		wp_register_script( 'filterable', get_template_directory_uri() . '/js/filterable.js', array( 'jquery' ) );
    		wp_enqueue_script( 'filterable' );
    	
    	add_action('wp_enqueue_scripts', 'enqueue_filterable');
    

    Now, back to the page_portfolio_2c.php file and below the last code added but inside the content div, add the following code:

    	
    

    This only links the plugin to the page and calls the filterable() function to make our portfolio filterable.

    Full Code

    
    
    
    
    		
    '; echo '
  • All
  • '; if ( $count > 0 ) foreach ( $terms as $term ) $termname = strtolower($term->name); $termname = str_replace(' ', '-', $termname); echo '
  • '.$term->name.'
  • '; } echo ""; ?> 'project', 'posts_per_page' => -1)); $count =0; ?>
      have_posts() ) : $loop->the_post(); ?> ID, 'tagportfolio' ); if ( $terms && ! is_wp_error( $terms ) ) : $links = array(); foreach ( $terms as $term ) $links[] = $term->name; $links = str_replace(' ', '-', $links); $tax = join( " ", $links ); else : $tax = ''; endif; ?>
    • Sorry, no portfolio entries for while.

    Step 5: Some style

    Now that we’ve coded everything that we need, let’s add some CSS to our style.css file, if you have other files just add the code there.

    /* CLEARFIX
    ----------------------------------------------- */
    
    .clearboth 
    	display: block;
    	margin: 0;
    	padding: 0;
    	clear: both;
    
    
    /* PORTFOLIO FILTER STYLE
    ----------------------------------------------- */
    
    #portfolio-filter 
    	list-style-type: none;
    
    
    #portfolio-filter li 
    	display: inline;
    	padding-right: 10px;
    
    
    #portfolio-filter li a 
    	color: #777;
    	text-decoration: none;
    
    
    #portfolio-filter li .current,
    #portfolio-filter li:hover 
    	color: #084a9a;
    
    
    /* PORTFOLIO LIST STYLE
    ----------------------------------------------- */
    
    #portfolio-wrapper 
    	padding-bottom: 25px;
    
    
    #portfolio-list 
    	list-style-type: none;
    
    
    
    #portfolio-list .portfolio-item 
    	width: 400px;
    	float: left;
    	margin-right: 5px;
    
    
    #portfolio-list .portfolio-item h3 a 
    	color: #084a9a;
    	text-transform: uppercase;
    	font-weight: bold;
    
    
    #portfolio-list .portfolio-item .excerpt
    
    	text-align: justify;
    	font-size: 14px;
    	line-height: 18px;
    	padding-right: 15px;
    	margin-bottom: 5px;
    
    
    #portfolio-list .portfolio-item .excerpt a 
    	color: #555;
    
    
    #portfolio-list .portfolio-item .excerpt a:hover 
    	text-decoration: none;
    
    

    Now, if you test again you’ll get a nice filterable portfolio! Wow, all the work is done!


    Conclusion

    And it’s done! Now you know how to create an amazing filterable portfolio with a free jQuery plugin that you can use in any work that you do.

    I hope that you enjoy the content, thank you very much for reading!

    Original from: http://wp.tutsplus.com/tutorials/creating-a-filterable-portfolio-with-wordpress-and-jquery/