K2 Joomla extension tutorial

The K2 Joomla extension was built as a complete replacement for Joomla's default article system. K2 adds important features that Joomla misses like comments, image auto-resizing and author profile pages. It gives Joomla a level-up as a blogging platform, adding the features that make WordPress great. Joomla has the plus of having tons of settings which allow to personalize the exact behaviour of pretty much everything.

CMSes and extra fields

The one feature I've always considered indispensable in a Content Management System is extrafield (as called in K2) or custom field (as called in WordPress) capability. Extra fields are simply text fields, text areas, dropdowns, links or images you add to an Article's Edit Page. You can then fill them and insert them into your template and give each its own position and styling. You can either use extra fields to add bits of related information to an article (a recommended resources section, for example) or you can forget about articles, and base your website completely in extra fields. An e-commerce site for example, could use an extra field to store product prices, another one for product weights and so on. Extra fields are the answer when you want to create anything different from a traditional article. Extra fields are not always extra. They allow you to go beyond normal articles and build more advanced websites without having to code them from scratch. K2 makes using extra fields incredibly simple, while also giving you control over loads of settings.

The Tutorial

This tutorial aims to get you started in using K2 Joomla extension as a CMS to, for example, run an online catalog, directory, e-commerce site, or simply creating custom feature-rich blog articles. No previous K2 experience is assumed, but a basic understanding of Joomla is. HTML, CSS and basic PHP knowledge will be required for customizing templates. If you already are a K2 user you may want to skip some of the first sections.

I'll create a book directory as example, adding extra fields for author, publisher, ISBN and number of pages. Note that we don't need extra fields for the title, image, description and category. All K2 items have a featured image (may be disabled), title, and main text which will work just fine. We will use the main article text for a description. K2 has built-in categories and tags. We will make use of them to classify our items (books). The proccess is pretty straightforward. I encourage you to change the extrafields and layout to build whatever site you have in mind instead of following the example.

Installing the K2 Joomla extension

The first step is downloading and installing Joomla if you haven't already. The latest Joomla 3.x and latest version of K2 are recommended for new sites. The easiest way to install K2 is directly from the Joomla Administration Panel. Go to Extensions -> Extension Manager -> Install from Web (enable the tab if prompted), search for "K2" and install it.

Note the new Icons in Joomla Control Panel:

Joomla K2 admin panel

K2 doesn't really replace the default Joomla Article System. It rather adds another system, leaving Joomla's articles right there. You can still use them, though it would be pretty confusing to mix Joomla and K2 articles. Therefore, it's good to know what is Joomla and what is K2 in the Control Panel. Basically, the Content dropdown in the top menu and the whole left sidebar in the Control Panel main page, all link to Joomla articles and categories. We won't be using those. Note that K2 calls content units Items, not Articles. The new icons in the main page are the K2 control panel. When using K2, those are the ones you normally want to use.

K2 doesn't replace the Joomla templating system. It rather adds its own templates, which control just the content portion of the site. The rest of the layout: header, footer, menus and other modules, is completely controlled by Joomla. This means we have to override both Joomla and K2 templates in order to completely customize the look of our website. We'll start with the Joomla template.

Customizing Joomla Templates

The easiest way to create a Joomla template is to edit an existing one. First copy an existing template from the Admin Panel. Go to the Template Manager, switch to view "Templates" (not "Styles"), click on a template you like (I'll be using Protostar), click "Copy Template" and give it a name. I'll call it "MyTemplate".

We will be editing only the K2 template for this simple tutotial. I'll just give you an overview on where and how to edit the main Joomla template. You'll have to know some HTML and CSS and at least a bit of PHP. The three most important files in most templates are:

  • index.php - The main template which calls Joomla content and inserts them into the different positions. Positions are spots defined by the template precisely for placing modules (menus, login forms, breadcrumbs, etc). You can select the position of a module from the Module Manager. The modules for a position are included with code like:
  • templateDetails.xml - This XML file is read by Joomla and defines quite a few things like name, version, author and description of the template. However, the most important thing it defines are the names of the positions the template uses. To create a position, first add its name to the section (eg. <position>main-menu</position>), then include it from the index.php file and then assign a module to it from the Module Manager.
  • css/template.css - The main stylesheet of the template. It may have another name, but it should be easy to locate it. This is the one you want to edit to change the default look.

You may edit those files using Joomla's Editor (Template Manager -> Templates -> mytemplate -> index.php) or, even better, your own editor if you have FTP access or a local server. The template folder is mysite/templates/mytemplate/.

Creating Extra Fields

We are getting to the good part. K2 extra fields are grouped in Extra Field Groups, which are in turn assigned to Categories. You can think of a K2 category as a type of item, which may or may not have a set of extra fields. For example, suppose we want a Blog in our Book Directory website. Blog items don't need extra fields, or at least, not the same as Books do. Then we would have to create two categories, Books and Blog Posts and assign the Extra Field Group only to the Books category.

To create an extra field, in the K2 administration panel, go to Extra Fields -> New:

Joomla K2 new extra field form

Give it a name (eg. ISBN) and an alias (eg. isbn). You may use the name in the template later so give it a meaningful and name and capitalize it. You are going to use the alias to identify the extra field from within the K2 template, so use a meaningful alias too. Follow a convention to facilitate remembering them. Write an Extra Field Group name in the Group section. I'll simply use "book". There are several types of fields but the most common and flexible are Text-Field, Textarea and Dropdown. Do check the list of types to see which fits best. We could have used the Date type, for example, to save the publication date of our books.

Set it as "Required" to disallow saving an item without filling the field. I prefer to set most of my fields as not required and handle empty fields in the template file. However, depending on what you're building some fields might be required.

Keep adding fields to the same Extra Field Group. I added author, publisher, ISBN and number of pages, all as text fields. Finally we have to assign the Extra Field Group to a K2 category. To do it, create a new K2 category (not Joomla category) and select your Extra Field Group name from the "Associated Extra Fields Group" dropdown:

K2 Joomla: associate extra field to category

We have everything set up. Now gow to Items -> New, select the proper Category, and you should be able to fill in the fields in the Extra Fields tab:

joomla-k2-article-extra-fields

Go ahead and add a test Item. Insert some content (Content tab) to use as description and upload an item Image. To view the item, it's necessary to add the Category or Item to a Joomla Menu. K2 adds several Menu Item Types to Joomla, which allow to link K2 content from Menus. We'll add a link to the Books category in the Main Menu. Go to Menus -> Main Menu -> New. Give it a title, which will appear as the link text (eg. Books). In Menu Item Type, select Categories from the K2 section. Note that you may also add direct links to Items, edit forms (that allow users to edit K2 Items), Latest Item pages, Tag pages and User pages. Finally chose "Main Menu" as Menu Location. Preview the site and you should see the new Item in the main menu:

Joomla Main Menu

In the test Item page, K2 inserts the extra fields in a table at the bottom of the page:

K2 Joomla extra fields table

You may create new menus from the Menu Manager, assign them Positions and add Menu Items linking to K2 content.

Customizing the K2 Template

Now that we have a way to access the single Item page, it's time to customize it. While Joomla renders the site header, menus, breadcrumbs, sidebar, footer and modules in general; K2 renders the Item title, body and comments. K2 has a default template that we want to override in order to provide a custom look to the content.

To override the default K2 template, copy the "default" folder in mysite\components\com_k2\templates\ ("default" has some PHP template files in it) and paste it to mysite\templates\mytemplate\html\com_k2\ (create the com_k2 folder). Then change the folder's name from "default" to whatever you like. I'll use "myk2template". Just to check, you should have the PHP template files in mysite\templates\mytemplate\html\com_k2\myk2template\.

Next you just have to assign the K2 template to a category. This is done from the K2 Categories page. Click the category you want to override to edit it ("Edit category" page) and select your template in the first dropdown to the right:

K2 template override

If the name of the folder doesn't appear in the dropdown, check if the folder is in the right place and if your custom Joomla template is active (important!). Next step is editing the K2 template files. You'll probably want to start with item.php, the one used to display a single Item.

You can go two different ways. Either make changes to the default item.php file or start from scratch, using the default as a reference. If your Items are very different from the classical blog post, I would start with a blank file and copy the most important parts of the default item.php. Here's the PHP code with just the bare essentials, to get you started:

<?php // no direct access
defined('_JEXEC') or die;
$item = array();
// Extra field array indexed by field alias
foreach($this->item->extra_fields as $extrafield){    
	$item[$extrafield->alias] = $extrafield;
} ?>

<div id="k2Container">
	<?php /*
	The k2Container is your playground. Insert the extra field data using:
		<?php echo $item['extra-field-alias']->name; ?>
		and
		<?php echo $item['extra-field-alias']->value; ?>
	The example fields are commented below.
	*/ ?>
	
	<div class="itemHeader">
	  <!-- Item title -->
	  <h2 class="itemTitle">
	  	<?php echo $this->item->title; ?>
	  </h2>
	  
	  <?php /* if(!empty($item['author'])): ?>
	  <!-- Book Author -->
	  <div class="itemAuthor itemField">
	      By <strong><?php echo $item['author']->value; ?></strong>
	  </div>
	  <?php endif; */ ?>
    </div>
  
    <div class="itemBody">
		<?php if($this->item->params->get('itemImage') && !empty($this->item->image)): ?>
	    <!-- Item Image -->
	    <div class="itemImageBlock">
		    <img src="<?php echo $this->item->image; ?>" alt="<?php echo K2HelperUtilities::cleanHtml($this->item->title); ?>"/>
			
			<?php /* if(!empty($item['isbn'])): ?>
			<!-- Book ISBN -->
			<div class="itemIsbn itemField">
				<strong><?php echo $item['isbn']->name; ?></strong>: <?php echo $item['isbn']->value; ?>
			</div>
			<?php endif; */ ?>
	    </div>
	    <?php endif; ?>
		
		<?php if($this->item->params->get('itemIntroText')): ?>
	    <!-- Item IntroText, used as a description -->
	    <div class="itemFullText"><?php echo $this->item->introtext; ?></div>
	    <?php endif; ?>
		
		<?php /* if(!empty($item['pages'])): ?>
		<!-- Book's number of pages -->
		<div class="itemPages itemField">
			<strong><?php echo $item['pages']->name; ?></strong>: <?php echo $item['pages']->value; ?>
		</div>
		<?php endif; */ ?>
		
		<?php /* if(!empty($item['publisher'])): ?>
		<!-- Book Publisher -->
		<div class="itemPublisher itemField">
			<strong><?php echo $item['publisher']->name; ?></strong>: <?php echo $item['publisher']->value; ?>
		</div>
		<?php endif; */ ?>
		
		<div class="itemContentFooter">
				<?php echo JText::_('K2_LAST_MODIFIED_ON'); ?> <?php echo JHTML::_('date', $this->item->modified, JText::_('K2_DATE_FORMAT_LC')); ?>
		</div>
    </div>
</div>

Styling K2

Whether you work with the above code or just modify the default K2 template, you are going to need a stylesheet to customize the layout. K2 adds a default stylesheet to the <head>, which has some basic styles. However there is no way to override this stylesheet, which is output by the K2 core. Changing the file directly is not a good idea as it may be overwritten when K2 is updated. I recommend removing this file from the documents <head>. To disable it go to Joomla's Global Configuration -> K2 component, and select Disable in "K2 Default CSS" section.

Where to write the CSS then? Simply add your styles to the bottom of the Joomla template's template.css file. This way your visitor's browsers will have to load one less file. You can copy K2's default CSS or write your own. Once again, if you are building something radically different from a blog post, writing your own CSS is more than worth the hassle. I just added a couple of styles:

.itemField {
	margin:8px 0;
}
.itemFullText {
	margin:15px 0;
}
.itemImageBlock {
	float:left;
}
.itemAuthor {
	font-size: 0.9em;
	margin:0;
	color:#767676;
}
.itemContentFooter {
	clear:both;
}

... and finally got an styled example Item:

K2 tutorial final layout

It's over. I hope the tutorial was of help. K2 Joomla extension is huge and there's much more to be said about K2 development. I'll be writing more articles on further customizing K2 templates, including item galleries, comments and URLs, not covered in this tutorial. Please follow codeitdown on Twitter, Facebook or sign up to the RSS feed to get updates on new K2 and web development and design articles.

Leave your feedback and any issues below. I'll be glad to help.

3 comments

  1. Thanks, Jose. This has helped me customize K2 for use with with a Gantry-based Joomla template from Crosstec. Well done!

  2. Thank you very much for this tutorial! I am an experienced webdesigner, but a Joomla/K2 newbie. This was just the right article to get me started on this platform. Very well written, I really appreciate your efforts!

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>