Archive for July, 2014

Joomla Tutorial

Here, I am demonstrating “how to create a Joomla site” easily. Here, I am making a website for a Computer Hardware Sjop in Joomla.

1. Download Joomla at http://www.joomla.org/download.html
2. Select and download  Joomla 3.3. Extract it to your server web root i.g, for me, it is; C:/wamp/www/joomla/
3. Download JCE editor. for Joomla. The default editor for Joomla is TinyMCE. You need to replace it by JCE editor. It provides much more facilities.

Download it from https://www.joomlacontenteditor.net/
Installing JCE

Download the .zip file to your hard disk (let say it is your desktop).

4. Create a database in MySQL let say “joomla” (you can use any name for the database)
5. Now, run the joomla project in the browser. For me it is; http://localhost:81/joomla
6. You will see a installation screen on the compute. Provide all details and click “Next” button.
2
7. 
Now, provide database details and click “Next”

3

4. In “Overview” section, click “Install” button to install. After installation, a button will appear “Remove Installation Folder”. Click it to remove, installation folder.
4

5. Open “Site” and “Administrator” both on separate tabs. So, that we can use administration panel and see it’s results in the site simultaneously.

You can also the admin panel by http://localhost:81/joomla/administrator/ i.e, http://<host name>:<port number>/<project folder name>/administrator/

6. Open the administration panel and login there.

7. First, we need to install the JCE, that we have already downloaded. Go to Extensions -> Extension Manager.
Click on “Browse” button, select the .zip file of JCE and click “Upload & Install” button.

5
8. After installation is completed, go to System -> Global Configuration menu.
Select default editor as “Editor – JCE” and click “Save & Close” button

6
Creating Categories:

9. Now go to Content -> Category Manager menu.
There exists a “Uncategorised”. Be it there. Click “New” button.

78

10. Enter title “About Us” and click “Save & New”
11. Enter “Products” and click “Save & New”
12. Enter “News” and click “Save & New”
13. Enter “Events”, select Parent as “News” and click “Save & New”
9
14.  Enter “Contact Us” and click “Save & Close

(Preparing and updating Part-2 Soon…..)

Advertisements

WordPress is gaining more and more popularity each day, not just as a blogging platform but also as a basic CMS, thus improving and extending its basic functionality becoming a day-to-day necessity for a lot of developers. Fortunately, the WordPress developers have foreseen these needs and added the possibility of customizing the basic functionality by adding plugins. Basicaly, a WordPress plugin is a (more or less) stand-alone piece of code that can be executed in different sections and stages within a page or site.

In today’s tutorial we’ll be talking about creating a WordPress plugin that extracts and displays products from an external OSCommerce shop database. We will start by describing the file structure of a plugin and where it must be included in the WordPress structure, then we’ll be having a closer look at how to make our plugin visible for WordPress and integrating it with actions run by its frame. Next, we’ll be creating a configuration panel for our plugin to allow the site administrator to customize it to his/her needs. Once done, we’ll be implementing the front-end functions themselves that will interact with the OSCommerce database and extract the required data. Finally, we’ll be modifying the default template to display the extracted data in the sidebar. Excited? Let’s get started!

Final Product

While it would be possible to follow this tutorial by simply reading through it, I would recommend installing WordPress on your computer and follow the tutorial implementing all the steps. For this, you’ll need a local server running on your machine, like XAMPPfor instance. Once you have it running, download and install WordPress. You will find extensive information about the installation process and troubleshooting on the WordPress site. For this tutorial we will be using release 2.7

Further on, you will need to set up an OSCommerce shop on your machine. You can download the latest release here: http://www.oscommerce.com/solutions/downloads

First, we’ll need to create our basic files and folder structure. WordPress stores its plugins in the wp-content/plugins/ folder. This is the place where we’ll be adding our files as well. Normally, if your plugin is going to be very simple, you will include all the code inside one single PHP file. In this case, you will simply store the file in the folder mentioned above. However, in our case, we are going to use two files (one for the main plugin file and one for implementing the administration page) therefore we’ll be putting all our files in a specific folder that we’ll name oscommerce_importer. Go ahead and create this folder.

Next, we must create our main plugin file. We’ll name it oscommerce_importer.php. You can really name it whatever you want, it doesn’t make any difference.

If you now open your WordPress administration panel and navigate to the Pluginssections, your screen will look something like this:

Admin panel

As you can see, there is not the slightest sign of our new plugin. It’s time to change that and tell WordPress that our file is going to implement a plugin. The process to do so is very simple. All we need to do is add a plugin specific information header to our newly created file. This standard header will look like this:

01
02
03
04
05
06
07
08
09
10
<?php
    /*
    Plugin Name: OSCommerce Product Display
    Plugin URI: http://www.orangecreative.net
    Description: Plugin for displaying products from an OSCommerce shopping cart database
    Author: C. Lupu
    Version: 1.0
    Author URI: http://www.orangecreative.net
    */
?>

Simple enough, don’t you think? You can, of course, change the content of this header to your liking but make sure you keep all the lines, otherwise WordPress won’t correctly recognize your plugin.

If you refresh your administration panel’s plugin page, you’ll now see our plugin listed along with the other ones.

Admin panel with deactivated plugin

See how all the relevant information like name, description, author, URL are extracted from the information header? This is why it is always important to correctly fill out this information. Let’s go and activate our plugin by clicking Activate to the right of the plugin entry.

Our plugin is now shown in the administration panel so WordPress is aware of it. However, it doesn’t do anything as it contains nothing except of the information header. We are going to change this now.

WordPress offers a great way to include your plugin code in different places all over the template, be it physical positions within a page or logical positions within the process of building up a page that is going to be displayed. First, we are going to have a closer look at the second category, the logical positions, better known as action hooks.

You can view action hooks as callback function. Whenever WordPress is executing a certain operation, like, for instance, displaying the page footer, it will allow your plugins to execute their own code that must be run at that exact moment.

For a better understanding, let’s consider a generic plugin called my_plugin that implements a function called mp_footer() that has to be run whenever the page footer is displayed. We will tell WordPress to call this function, at the moment of displaying the footer by using a special function called add_action():

1
<php add_action('wp_footer', 'mp_footer'); ?>

The add_action() function takes the action hook name as its first parameter and the name of the function that must be executed, as a second parameter. This function call will be added to your main plugin file (the one containing the information header), usually, right under the function code that needs to be executed (mp_footer() in our example). You will find the full list of available action hooks in the WordPress Codex.

We’ll be using action hooks in the next chapter, where we are going to build the administration page for our plugin.

We’ll start the implementation of the module by defining its configurable parameters and make these accessible to the site administrator. Let’s see what these configuration bits would be:

  • Database settings
    • database host
    • database name
    • database user
    • database password
  • Store settings
    • store URL
    • folder for the product images

First, we need the database host, name, user and password in order to be able to connect to it and extract the needed data. Second, we need some general data about the store like its URL and the folder where the product images are stored. We need this information in order to be able to build the links because the paths contained in the database are all relative the previously mentioned product image folder.

Now that we know what we want to include in the configuration panel, it’s time to implement it. We’ll start by creating a new menu item to access the page and we’ll place it inside the Settings menu. Remember our chat about the action hooks in the previous chapter? It’s time to use this feature.

If you’ll scroll over the list of action hooks, you’ll see that WordPress also provides one that gets called when the basic menu structure has been generated (admin_menu) so, this would be the optimal place to chime in and create our own menu item.

Now that we identified the action we are going to use, all we need is to define our own function that will be called when this action hook runs. We’ll call our functionoscimp_admin_actions() where oscimp_ stands for oscommerce importer and is used to create a possibly unique function name that will not get mismatched with any other function within WordPress or any of its plugins. Let’s see how the code will look like:

1
2
3
4
5
function oscimp_admin_actions() {
}
add_action('admin_menu', 'oscimp_admin_actions');

As you can see, we are creating our function oscimp_admin_actions() then associate it with the admin_menu action hook using the add_action() function. The next step would then be to add some code to our oscimp_admin_actions() function to actually create the new menu item.

As with most WordPress things, adding a new menu item is also very easy. It all boils down to calling a single function. We would like to add our new menu item to theSettings menu so, in this case the function we need is add_options_page(). We’ll add the code inside the oscimp_admin_actions() function.

1
2
3
4
5
function oscimp_admin_actions() {
    add_options_page("OSCommerce Product Display", "OSCommerce Product Display", 1, "OSCommerce Product Display", "oscimp_admin");
}
add_action('admin_menu', 'oscimp_admin_actions');

If you refresh your admin page, you’ll see the new menu item appear under Settings.

New menu item

Each existing menu has its own function to be used to add sub-menu items. For instance, if we would like to add our sub-menu item to the Tools menu instead ofSettings, we would use the add_management_page() function instead ofadd_options_page(). You can find more details about the available options in theAdding Administration Menus section of the WordPress Codex.

If we get back to the newly added code line, you’ll probably notice the last parameter. This is actually a function name that will be called when the newly added menu item is clicked on and will be used to build the administration page of our plugin. Next, we’ll be adding this new function. However, before proceeding we should stop for a moment and think about what will be implemented on this page.

We already defined the parameters we want to make configurable (database host, name, user, etc) so these will have to be included in a form in order to allow the user to send the data to the database. Once the form is defined, we’ll need a bit of code that extracts the sent data from the form and saves it to the database. Last but not least, we need some code to extract the existing data from the database (if any) and pre-populate the form with these values. As you can see, there are quite a few things to do so, it might be a good idea to separate this functionality to its own file. We’ll name the file oscommerce_import_admin.php. Now, go and create an empty file with the given name.

As already mentioned, we’ll have to create the function that will display our plugin configuration page (we named this function oscimp_admin()). The code inside this function will be included from our newly created PHP file,oscommerce_import_admin.php

1
2
3
4
5
6
7
8
9
function oscimp_admin() {
    include('oscommerce_import_admin.php');
}
function oscimp_admin_actions() {
    add_options_page("OSCommerce Product Display", "OSCommerce Product Display", 1, "OSCommerce Product Display", "oscimp_admin");
}
add_action('admin_menu', 'oscimp_admin_actions');

If you now click on the link under the Settings menu, you will be directed to an empty page. This is because our oscommerce_import_admin.phpfile is still empty.

Empty plugin configuration page

Next, we are going to create our form. For this we’ll use the following code:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
<div class="wrap">
    <?php    echo "<h2>" . __( 'OSCommerce Product Display Options', 'oscimp_trdom' ) . "</h2>"; ?>
    
    <form name="oscimp_form" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
        <input type="hidden" name="oscimp_hidden" value="Y">
        <?php    echo "<h4>" . __( 'OSCommerce Database Settings', 'oscimp_trdom' ) . "</h4>"; ?>
        <p><?php _e("Database host: " ); ?><input type="text" name="oscimp_dbhost" value="<?php echo $dbhost; ?>" size="20"><?php _e(" ex: localhost" ); ?></p>
        <p><?php _e("Database name: " ); ?><input type="text" name="oscimp_dbname" value="<?php echo $dbname; ?>" size="20"><?php _e(" ex: oscommerce_shop" ); ?></p>
        <p><?php _e("Database user: " ); ?><input type="text" name="oscimp_dbuser" value="<?php echo $dbuser; ?>" size="20"><?php _e(" ex: root" ); ?></p>
        <p><?php _e("Database password: " ); ?><input type="text" name="oscimp_dbpwd" value="<?php echo $dbpwd; ?>" size="20"><?php _e(" ex: secretpassword" ); ?></p>
        <hr />
        <?php    echo "<h4>" . __( 'OSCommerce Store Settings', 'oscimp_trdom' ) . "</h4>"; ?>
        <p><?php _e("Store URL: " ); ?><input type="text" name="oscimp_store_url" value="<?php echo $store_url; ?>" size="20"><?php _e(" ex: http://www.yourstore.com/" ); ?></p>
        <p><?php _e("Product image folder: " ); ?><input type="text" name="oscimp_prod_img_folder" value="<?php echo $prod_img_folder; ?>" size="20"><?php _e(" ex: http://www.yourstore.com/images/" ); ?></p>
        
    
        <p class="submit">
        <input type="submit" name="Submit" value="<?php _e('Update Options', 'oscimp_trdom' ) ?>" />
        </p>
    </form>
</div>

If you are familiar with HTML and PHP, the code above will make some sense but, still, let us shortly walk through the lines.

  • We start by creating a div with the class wrap. This is a standard WordPress class that will make our page look like any other page in the administration area.
  • The form will be using the POST method to send data back to itself. This means that the form data will be received by the same page so, we can add the database update code to the same file.
  • Next, there is a hidden field that will be used to determine whether the current page is displayed after the user has pressed the Update Options button or not. When the page receives the form data, the value of this field will be set to Y.
  • The next lines will create the form input fields for the database and store settings. As you can easily see, the value parameters are be set by the content of PHP variables. We’ll talk about these soon.
  • Now if you refresh the admin page, you’ll see our newly created form. However, pressing the Update Options button will have no effect other than refreshing the page and the form fields are empty.
Plugin configuration page with form

Once the form is ready to go, we’ll take care of the form data handling itself, updating the database and retrieving existing option values from the database. For this, we’ll first have to decide whether the current page is displayed after the user has pressed theUpdate Options button or not. We’ll do this by analyzing the value of the form’s hidden field, oscimp_hidden. The following code will be added at the very beginning of ouroscommerce_import_admin.php file, before the code for displaying the form:

1
2
3
4
5
6
7
<?php
    if($_POST['oscimp_hidden'] == 'Y') {
        //Form data sent
    } else {
        //Normal page display
    }
?>

Next, we’ll be handling the form data and update the plugin options in the database accordingly. For this we’ll be using the update_option() function. The first parameter of this function is the option name which will be sued later to uniquely identify this option and its value. The second parameter is the value to be assigned.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
    if($_POST['oscimp_hidden'] == 'Y') {
        //Form data sent
        $dbhost = $_POST['oscimp_dbhost'];
        update_option('oscimp_dbhost', $dbhost);
        
        $dbname = $_POST['oscimp_dbname'];
        update_option('oscimp_dbname', $dbname);
        
        $dbuser = $_POST['oscimp_dbuser'];
        update_option('oscimp_dbuser', $dbuser);
        
        $dbpwd = $_POST['oscimp_dbpwd'];
        update_option('oscimp_dbpwd', $dbpwd);
        $prod_img_folder = $_POST['oscimp_prod_img_folder'];
        update_option('oscimp_prod_img_folder', $prod_img_folder);
        $store_url = $_POST['oscimp_store_url'];
        update_option('oscimp_store_url', $store_url);
        ?>
        <div class="updated"><p><strong><?php _e('Options saved.' ); ?></strong></p></div>
        <?php
    } else {
        //Normal page display
    }
?>

The code above if pretty much self-explanatory but please note that here we are using the PHP variables we have previously mentioned while building the form. These variables will be updated with the current form data values and will be displayed in the form itself. Go, check it out! Refresh the configuration page and enter your OSCommerce database settings as well as your store parameters then press Update Options.

If everything was implemented like described above, you’ll see an Options savedsuccess message and the form fields will contain the data you have just entered.

Plugin configuration page with success message

Last but not least, we’ll need to pre-populate the form with the database data when the user opens the configuration page. For this, we’ll be using the get_option() function which retrieves the specified option from the database.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
    if($_POST['oscimp_hidden'] == 'Y') {
        //Form data sent
        $dbhost = $_POST['oscimp_dbhost'];
        update_option('oscimp_dbhost', $dbhost);
        
        $dbname = $_POST['oscimp_dbname'];
        update_option('oscimp_dbname', $dbname);
        
        $dbuser = $_POST['oscimp_dbuser'];
        update_option('oscimp_dbuser', $dbuser);
        
        $dbpwd = $_POST['oscimp_dbpwd'];
        update_option('oscimp_dbpwd', $dbpwd);
        $prod_img_folder = $_POST['oscimp_prod_img_folder'];
        update_option('oscimp_prod_img_folder', $prod_img_folder);
        $store_url = $_POST['oscimp_store_url'];
        update_option('oscimp_store_url', $store_url);
        ?>
        <div class="updated"><p><strong><?php _e('Options saved.' ); ?></strong></p></div>
        <?php
    } else {
        //Normal page display
        $dbhost = get_option('oscimp_dbhost');
        $dbname = get_option('oscimp_dbname');
        $dbuser = get_option('oscimp_dbuser');
        $dbpwd = get_option('oscimp_dbpwd');
        $prod_img_folder = get_option('oscimp_prod_img_folder');
        $store_url = get_option('oscimp_store_url');
    }
?>

You can test the code above by simply navigating to another page within the admin area and then retuning to this page by clicking the OSCommerce Product Display sub-menu item in the Setting menu. If everything goes well, you will see the form with all the fields pre-populated with the data you have entered.

Plugin configuration page with pre-populated form

With this last piece of code, we have finished implementing the plugin’s configuration page so, let’s review what has been done in this chapter:

  • we defined what parameters need to be configured by the site administrator
  • we added an action hook for when the menu is displayed in the administration panel to help us add a new sub-menu item for our plugin
  • we have added a new sub-menu item to the Settings menu that will link to our plugin’s configuration page
  • we have defined a function that will build the plugin’s configuration page and separated its code in a second PHP file
  • we have built the form containing the user inputs for each of the configurable data bits
  • we have built the database update function
  • we have built a function that will pre-populate the form with the option values stored in the database

Well, everything went quite fine so far but our plugin is yet unusable because we haven’t implemented the part that will actually allow us to display the products in the front-end.

In order to allow our users to display the products in the front-end, we’ll need to declare a function that can be called from the template’s PHP code and which will return the HTML code to be inserted in the template. We are going to name this functionoscimp_getproducts() and accept the number of products to be displayed as a function parameter. The function itself will be implemented in our plugin’s main file,oscommerce_import.php

1
2
3
function oscimp_getproducts($product_cnt=1) {
}

As you can see, we are assigning a default value to our function parameter thus allowing our users to call the function both with and without a parameter. If the function is called with a parameter, like oscimp_getproducts(3), it will display three products. If the function is called without a parameter, like oscimp_getproducts(), it will only display one product.

First thing in our function would be to establish a connection to the OSCommerce database. Thanks to our plugin configuration page, we now have all the information we need: database host, name, user and password. We’ll be using the built-in wpdb class to create a new database object.

1
2
3
4
function oscimp_getproducts($product_cnt=1) {
    //Connect to the OSCommerce database
    $oscommercedb = new wpdb(get_option('oscimp_dbuser'),get_option('oscimp_dbpwd'), get_option('oscimp_dbname'), get_option('oscimp_dbhost'));
}

Once this is done, we declare a variable that will contain the HTML code and start quering the OSCommerce database for each of the specified number of products. The code below merely implements this query loop and can be further-on improved by checking for duplicates, for instance, but this is not the subject of this tutorial so, we’ll keep it simple for the sake of readability.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function oscimp_getproducts($product_cnt=1) {
    //Connect to the OSCommerce database
    $oscommercedb = new wpdb(get_option('oscimp_dbuser'),get_option('oscimp_dbpwd'), get_option('oscimp_dbname'), get_option('oscimp_dbhost'));
    $retval = '';
    for ($i=0; $i<$product_cnt; $i++) {
        //Get a random product
        $product_count = 0;
        while ($product_count == 0) {
            $product_id = rand(0,30);
            $product_count = $oscommercedb->get_var("SELECT COUNT(*) FROM products WHERE products_id=$product_id AND products_status=1");
        }
        
        //Get product image, name and URL
        $product_image = $oscommercedb->get_var("SELECT products_image FROM products WHERE products_id=$product_id");
        $product_name = $oscommercedb->get_var("SELECT products_name FROM products_description WHERE products_id=$product_id");
        $store_url = get_option('oscimp_store_url');
        $image_folder = get_option('oscimp_prod_img_folder');
        //Build the HTML code
        $retval .= '<div class="oscimp_product">';
        $retval .= '<a href="'. $store_url . 'product_info.php?products_id=' . $product_id . '"><img src="' . $image_folder . $product_image . '" /></a><br />';
        $retval .= '<a href="'. $store_url . 'product_info.php?products_id=' . $product_id . '">' . $product_name . '</a>';
        $retval .= '</div>';
    }
    return $retval;
}

Once this is done, all we have to do is insert the oscimp_getproducts() function call to the template. We’ll be displaying three products at the bottom of the sidebar so, we are going to modify the sidebar.php file of our template, inserting the following code right below the list item containing the meta links:

1
<li><?php echo oscimp_getproducts(3); ?></li>

If you refresh your front-end page now, you’ll see the three random products displayed at the bottom of the sidebar.

Frontpage with random products

With this last piece of code, we have finished implementing the front-end function as well.

We have now implemented a WordPress plugin from scratch. Let’s summarize what has been done:

  • we defined the way we store our plugin files
  • we defined the information header in order to make our plugin visible for WordPress
  • we talked about the action hooks and the way these are used
  • we defined what parameters need to be configured by the site administrator
  • we added an action hook for when the menu is displayed in the administration panel to help us add a new sub-menu item for our plugin
  • we have added a new sub-menu item to the Settings menu that will link to our plugin’s configuration page
  • we have defined a function that will build the plugin’s configuration page and separated its code in a second PHP file
  • we have built the form containing the user inputs for each of the configurable data bits
  • we have built the database update function
  • we have built a function that will pre-populate the form with the option values stored in the database
  • we have built our user function for use in the template
  • we connected to the OSCommerce database
  • we queried the OSCommerce database extracting the product ID, image and name
  • we have built the HTML code for displaying the extracted data
  • we have included the user function to the template sidebar

Ref: http://code.tutsplus.com

“Custom post types aren’t really meant for that use. Custom post types are great for things that are more or less catalogued: products (in an e-commerce site), listings for a real estate site, etc. For regular content creation as described [by Chris], you can already do [that] by using custom taxonomies and/or stylesheets to make post templates.”

Now before we dig in I want to say this – custom post types make things a lot easy for non-technical people to use the WordPress admin to enter content. However the designer/developer still needs to have a reasonable grasp of PHP and needs to be prepared to get their hands dirty.

For our tutorial we’re going to be editing functions.php which is your theme directory. We’re simply adding to this file, so feel free to start at the top or at the bottom – just don’t change any of the code that’s already there. For the more confident of you out there you could adapt this code into a plugin.

With a few edits we are going to create a custom post type for our portfolio, and a template which will use this information. We’ll end up with a new panel in the admin menu which looks like this:

A new overview page called “My Portfolio”:

And a new place to enter our content:

Step 1

Here’s the first bit of code we need to add to functions.php, which I’ll review below.

add_action('init', 'portfolio_register');
 
function portfolio_register() {
 
	$labels = array(
		'name' =&gt; _x('My Portfolio', 'post type general name'),
		'singular_name' =&gt; _x('Portfolio Item', 'post type singular name'),
		'add_new' =&gt; _x('Add New', 'portfolio item'),
		'add_new_item' =&gt; __('Add New Portfolio Item'),
		'edit_item' =&gt; __('Edit Portfolio Item'),
		'new_item' =&gt; __('New Portfolio Item'),
		'view_item' =&gt; __('View Portfolio Item'),
		'search_items' =&gt; __('Search Portfolio'),
		'not_found' =&gt;  __('Nothing found'),
		'not_found_in_trash' =&gt; __('Nothing found in Trash'),
		'parent_item_colon' =&gt; ''
	);
 
	$args = array(
		'labels' =&gt; $labels,
		'public' =&gt; true,
		'publicly_queryable' =&gt; true,
		'show_ui' =&gt; true,
		'query_var' =&gt; true,
		'menu_icon' =&gt; get_stylesheet_directory_uri() . '/article16.png',
		'rewrite' =&gt; true,
		'capability_type' =&gt; 'post',
		'hierarchical' =&gt; false,
		'menu_position' =&gt; null,
		'supports' =&gt; array('title','editor','thumbnail')
	  ); 
 
	register_post_type( 'portfolio' , $args );
}

Anyone who’s worked with WordPress before will recognise the structure here. We’re adding an action when the WP Admin initialises to call the function portfolio_register(). In that function we create two arrays, $labels and $args, and then use register_post_type to pull it all together. In doing so we name the new custom post type ‘portfolio’ and tell it to use the arguments from$args.

The devil is in the detail, so let’s run over some of those arguments. A full list can be found at http://codex.wordpress.org/Function_Reference/register_post_type. First let’s look at $labels:

  • name this is the (probably plural) name for our new post type
  • singular_name how you’d refer to this in the singular (such as ‘Add new ****’)

You can probably work out the rest of $labels for yourself, as they simply refer to different circumstances in which the name of your custom post type would be used.

And now $args:

  • public should they be shown in the admin UI
  • show_ui should we display an admin panel for this custom post type
  • menu_icon a custom icon for the admin panel
  • capability_type WordPress will treat this as a ‘post’ for read, edit, and delete capabilities
  • hierarchical is it hierarchical, like pages
  • rewrite rewrites permalinks using the slug ‘portfolio’
  • supports which items do we want to display on the add/edit post page

That’s the first simple step, and it should be enough to see your new custom post time in the WordPress admin. Save functions.php and take a look!

Step 2

The next thing we need to do is register a taxonomy. Or, in English, create categories for this new content type.

For example, in our portfolio we want to include the names of technologies and software used to create our work. I’m going to call this taxonomy ‘Skills’, and populate it with things like HTML, CSS and jQuery.

It’s just one line of code:

register_taxonomy("Skills", array("portfolio"), array("hierarchical" =&gt; true, "label" =&gt; "Skills", "singular_label" =&gt; "Skill", "rewrite" =&gt; true));

The first item here is the taxonomy name, ‘Skills’. The second is the name of the object type we’re applying it to, in our case the custom post type ‘portfolio’ (which is an array). Finally our arguments; you can find a full list at http://codex.wordpress.org/Function_Reference/register_taxonomy, and here we’re using just three which have the same meaning as described in Step 1.

Add that line of code in and you should now see:

You can then enter new ‘skills’ just like you’d enter categories for blog posts. It looks like this:

Step 3

The third step is to add custom data fields to the add/edit post page.

For our portfolio we can add things like the year the piece was published and details on who designed, built and produced the site/design.

There’s a bit more code here, but read through it in order and it should make sense:

add_action("admin_init", "admin_init");
 
function admin_init(){
  add_meta_box("year_completed-meta", "Year Completed", "year_completed", "portfolio", "side", "low");
  add_meta_box("credits_meta", "Design &amp; Build Credits", "credits_meta", "portfolio", "normal", "low");
}
 
function year_completed(){
  global $post;
  $custom = get_post_custom($post-&gt;ID);
  $year_completed = $custom["year_completed"][0];
  ?&gt;
  &lt;label&gt;Year:&lt;/label&gt;
  &lt;input name="year_completed" value="&lt;?php echo $year_completed; ?&gt;" /&gt;
  &lt;?php
}
 
function credits_meta() {
  global $post;
  $custom = get_post_custom($post-&gt;ID);
  $designers = $custom["designers"][0];
  $developers = $custom["developers"][0];
  $producers = $custom["producers"][0];
  ?&gt;
  &lt;p&gt;&lt;label&gt;Designed By:&lt;/label&gt;&lt;br /&gt;
  &lt;textarea cols="50" rows="5" name="designers"&gt;&lt;?php echo $designers; ?&gt;&lt;/textarea&gt;&lt;/p&gt;
  &lt;p&gt;&lt;label&gt;Built By:&lt;/label&gt;&lt;br /&gt;
  &lt;textarea cols="50" rows="5" name="developers"&gt;&lt;?php echo $developers; ?&gt;&lt;/textarea&gt;&lt;/p&gt;
  &lt;p&gt;&lt;label&gt;Produced By:&lt;/label&gt;&lt;br /&gt;
  &lt;textarea cols="50" rows="5" name="producers"&gt;&lt;?php echo $producers; ?&gt;&lt;/textarea&gt;&lt;/p&gt;
  &lt;?php
}

First of all we call the add the admin_init function to the queue when the WordPress admin initialises, and within that function we add two meta boxes – places to enter our data. The context for these two statements is

&lt;?php add_meta_box( $id, $title, $callback, $page, $context, $priority ); ?&gt;

The only difference between the two is where we place them on the screen. The ‘year completed’ is placed in the sidebar using ‘side’ whilst the ‘credits’ are placed in the main flow of the page using ‘normal’.

Within the two functions there is some vanilla WordPress PHP code and HTML to help define our old friend custom fields. Make sure to include

global $post;

…so that we can then query the current post using

$custom = get_post_custom($post-&gt;ID);

Once the two new meta boxes have been added it looks like this:

The final thing to do in step 3 is to make sure we then save these values with this post. I do this with

add_action('save_post', 'save_details');

and

function save_details(){
  global $post;
 
  update_post_meta($post-&gt;ID, "year_completed", $_POST["year_completed"]);
  update_post_meta($post-&gt;ID, "designers", $_POST["designers"]);
  update_post_meta($post-&gt;ID, "developers", $_POST["developers"]);
  update_post_meta($post-&gt;ID, "producers", $_POST["producers"]);
}

There’s nothing too tricky here. Again we’re adding an action, this time to the ‘save_post’ event. It fires the function save_details() which uses update_post_meta (http://codex.wordpress.org/Function_Reference/update_post_meta) to save the relevant data.

Step 4

A nice little touch is to rejig the layout of the My Portfolio page to display some of this information. If you’ve followed through the article so far this should all make sense to you:

add_action("manage_posts_custom_column",  "portfolio_custom_columns");
add_filter("manage_edit-portfolio_columns", "portfolio_edit_columns");
 
function portfolio_edit_columns($columns){
  $columns = array(
    "cb" =&gt; "&lt;input type="checkbox" /&gt;",
    "title" =&gt; "Portfolio Title",
    "description" =&gt; "Description",
    "year" =&gt; "Year Completed",
    "skills" =&gt; "Skills",
  );
 
  return $columns;
}
function portfolio_custom_columns($column){
  global $post;
 
  switch ($column) {
    case "description":
      the_excerpt();
      break;
    case "year":
      $custom = get_post_custom();
      echo $custom["year_completed"][0];
      break;
    case "skills":
      echo get_the_term_list($post-&gt;ID, 'Skills', '', ', ','');
      break;
  }
}

Here we’re adding two more functions to the WordPress Admin. The first,portfolio_edit_columns($columns), simply defines the columns. The first two arguments “cb” and “title” are part of the core so don’t play with those too much (you can of course rename “Portfolio Title”). It’s the next three that come from our custom post type, “description”, “year” and “skills”.

We have one more function to tell WordPress where to get this data from –portfolio_custom_columns($column). Using a simple switch/case we can define what data to actually show in the column layout. For the “description” we use the_excerpt(), for “year” we get the custom field data using get_post_custom(), and for “skills” we get a comma separated list of the terms/taxonomies/categories using get_the_term_list().

With that we have our customised columns:

One final touch

Be default custom post types will display using single.php, or index.php as a fallback. The great thing is we can create our own custom template using the filename single-xxxxxx.php. In our case this is single-portfolio.php. Just create your template file in your theme directory and the custom post type will use it. How you display the data is totally up to you.

Hey, did you also notice the ‘Featured Image’ option on the add/edit page. That works out-of-the-box thanks to the ‘thumbnail’ part of:

'supports' =&gt; array('title', 'editor', 'thumbnail')

You just need to make sure to include the following line of code in functions.php:

add_theme_support('post-thumbnails');

For more details check out this excellent post by Mark Jaquith.

Rewrite Problems?

There are a few reported problems out there about the rewriting of custom URLs; in short, they sometimes don’t work. However, if you’re experiencing this problem there are a couple of easy fixes.

First, simply go to the Settings > Permalinks page, which will flush the permalinks (assuming that your WordPress install can write to the .htaccess file). This should clear up most problems related to permalinks, custom post type related or not.

If that doesn’t work you can add a line of code after you register the post type:

	register_post_type( 'portfolio' , $args );
        flush_rewrite_rules();

This worked for me on a particularly problematic install.

Conclusion

And there we have it! That is a whistle-stop tour of custom post types which I hope gives you the appetite to explore further.

The best thing is to experiment with the code, read through the documentation in the WordPress Codex, and share your ideas with others. Like any new feature I’m sure it will evolve as users create new and exciting ways to use it, and we’d love to hear about how you’re using custom post types here at Treehouse.

This article was written by Richard Shepherd.

You want to start your own blog but you don’t want to look tacky by using an existing design. Creating your own theme can be daunting, but with some assistance you can have a unique design for your blog in no time. This post will help you put it all together using WordPress, the most popular (and free) blogging software available.

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

Creating a WordPress theme can take quite a bit of work when you’re starting from scratch because you have to put together quite a bit of PHP code (the programming language WordPress uses) before you can even get to creating the look and feel of your site. We’re going to save you the trouble by providing those files pre-made for you, plus a skeletal structure of the CSS you’re going to need to make your WordPress site look the way you want. The PHP code is based upon the work of Ian Stewart, but has been updated for WordPress 3.3.1. If you’re ready to get started, here’s what you’ll need:

  • WordPress, installed and ready to go. During theme development we highly recommend running a local web server with PHP and WordPress installed so you’re not testing any changes you make live on your web server. This also makes development a lot faster. When you’re done, you can simply install the finished theme on your web server and it will be ready to go. If you want to develop locally, the easiest way to get started is with the self-contained web servers WAMP (Windows) or MAMP (OS X). They contain the Apache web server with PHP and MySQL ready to go, so you’ll be able to download and install WordPress quickly and easily. Once you’ve got your theme ready to go, installing WordPress on a proper server is generally quite easy. For example, our favorite beginner host, Dreamhost, features a one-click WordPress installation.
  • Our blank theme files. Download and unzip.
  • Basic knowledge of HTML and CSS (which you can obtain here).
  • A design you’ve made for your WordPress site (which you can learn how to do in Photoshop here).
  • Optional: If you don’t want to use the theme editor built into WordPress, you should get a programming-friendly text editor. (Here are our picks for Windows and OS X.)
  • Optional: Since you’re WordPress site is likely empty, and it’s hard to create a theme when there’s no content, you can download sample content (and import) for development purposes. This can be a big help in a local development environment where you’re not going to use the content. You probably don’t want to add it to a live site because 1) it’ll be visible, and 2) you’ll want to remove it after you’re done developing.

Once you’ve got everything, you’re ready to start making your theme!

Get to Know and Install Your Theme Files

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

When you unzip the lh_wordpress_blank_theme.zip file your downloaded, you’ll have a folder filled with a bunch of files and two folders. Here’s a quick list of what they are and what they do:

  • 404.php – The page responsible for displaying 404 not found errors, for when a user attempts to go to a page on your WordPress site that does not exist.
  • archive.php – Displays the archived posts list, much like the main page but for posts in the archive.
  • author.php – Displays all the posts for a particular author. It’s basically the same as the archives page, but just for one author.
  • category.php – Displays all the posts in a given category.
  • comments.php – When on a single post page and comments are accepted, this file will be used to show the comment form.
  • footer.php – The footer that will be inserted at the bottom of the page. You’ll need to edit this file and add what you want to show up in the footer.
  • functions.php – Custom functions for the theme. You should leave this alone unless you know PHP and know what you’re doing.
  • header.php – Displays the header at the top of every page on your WordPress site. This is the code that generates the menu.
  • img – A folder for custom images you’re using in your theme. You can leave this empty or delete it if you are not using custom images.
  • index.php – Displays the primary blog roll page. Like many other pages (e.g. author.php, page.php, search.php, etc.) in incorporates the header.php, sidebar.php, and footer.php files to display the entire site.
  • page.php – Displays any single page. This does not include posts, but rather individual static pages you’ve created in the WordPress Admin.
  • search.php – Displays search results a user requested through the search widget on your WordPress site. If no results are found, it will inform the user that it failed to bring up any results.
  • sidebar.php – This file contains the primary and secondary areas for sidebar widgets. You can add widgets to these areas via the WordPress Admin and shouldn’t need to edit this file.
  • single.php – Displays a single post with or without comments.
  • styles.css – This is the file we will be editing in this guide, so it has been highlighted in red. This contains the skeletal structure of the CSS you’ll need to make your WordPress site look the way you want it to look. The majority of your work will be in this file.
  • styles – A folder to contain any additional CSS files you may use or import. If you don’t use this, you can just delete it.
  • tags.php – Displays posts for a given tag.

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

That list probably seems a little intimidating, but chances are you won’t need to edit most of those files. We just wanted you to know what everything does. At the very least, you only need to edit styles.css, and maybefooter.php (if you want to add content to your footer). Now that you know what you’re in for, let’s install this blank theme in WordPress. To do so, just follow these steps:

  1. Log into your WordPress Admin section. You probably know where this is, but if not it is, by default, at http://yourdomain.com/wp-admin (or if you’re running WAMP/MAMP it is, by default, at http://localhost:8888/wp-admin).
  2. Go to the appearance tab on the left-hand menu and choose Appearance -> Themes.
  3. From the menu up top (which only has two tabs), choose Install themes.
  4. Click the Upload link.
  5. Click the Choose file… button to select the lh_wordpress_blank_theme.zip file you downloaded and then click Install Now.
  6. When the theme has been installed, click back to Appearance -> Themes and find it. It should by called Blank and have no preview image. When you see it, click the Activate link to make it the active theme.

Alternatively, if you prefer installing via FTP or just moving the files to the correct directory on your local machine, unzip the lh_wordpress_blank_theme.zip and rename it “blank” (or whatever you want). Now find the wp-content folder in your WordPress installation directory and open it. You’ll see a directory called “themes” inside. Copy blank into it, then follow the last step in the steps above to activate it on your WordPress site.

Style Your WordPress Theme

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

With the blank theme installed you’re ready to start making your WordPress theme look great. Currently, however, it looks like an ugly mess of blue, green, and black. It may not even look that good if you haven’t added a menu, widgets, or any content. If you still need to add content, either download sample content or create some of your own. Even if you install sample content, you’ll still need to go into the WordPress Admin, click on the appearance section, and edit both the Menus and Widgets subsections. Just head into the Widgets subsection and (literally) drag some widgets into both the primary and secondary sidebar spaces, then create a menu in the Menus subsection. Once you have all your (possibly fake) content ready, you’ll see it all on your WordPress site. It will probably look something like the image to the right.

Now that everything is in place, we need to start editing the styles.css file. You can either open it up in your favorite programming-friendly text editor, or you can go to the Appearance tab in the WordPress Admin section, choose Editor, and then choose styles.css from the right-hand menu (if it isn’t already selected by default). Either way, you should now see the skeletal CSS structure you’re going to use. It does not include every single style you may want to edit, but the main ones you’ll need to get most of your style together. (Later on we’ll discuss how you can discover other elements and how to style them as well, so if you want to take things further than the template we’ve provided you’ll be able to do so easily.) Since everyone’s design is going to vary a little bit, we’re going to discuss what most of the styles do rather than offering up specific code you can use. You’re going to need to bring your own design and CSS knowledge to the table, so if you’re feeling a little shaky you can brush up your skills with our CSS night school lesson. So, without further ado, here’s a rundown of the styles.css file. Each item we cover will demonstrate what it looks like now and what it could look like once you add some style.

Global: General Style Defaults

The General Style Defaults are pretty much laid out for you already and should be pretty familiar even if you don’t know very much CSS. For the most part these styles are just setting the margins of the document (which are currently at 0 pixels), the default font to use on the page, what colors the background and text are, how links look in their various states, and more. You can leave this information as-is, or go in and make general changes as desired. For the most part, the look and feel of your WordPress site won’t be too heavily influenced by these styles and, if anything, the changes you make will mostly relate to the fonts and colors.

Page Layout

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

The Page Layout section of the styles.css file contains only two code blocks: one fordiv#container and one for div#content. In both cases we’re targeting DIV tags. The one called container is what contains pretty much everything on the page that is not the header or the footer. That means you’ve got the post, static page, or blog roll, the comments, and the sidebar widgets all wrapped into this one container. By default we’ve given it a 4px margin to inset all this content just a tiny bit from the header. You can adjust it however you like and add any new styles you wish here. The content DIV, on the other hand, only includes the post, static page, or blog roll (and comments, if they’re visible). Any styles you add here will only effect that content. One of the first things you’re going to want to do is position this DIV somewhere on the page. Traditionally it is aligned left by using this CSS code:

float: left;

 

 

 

Chances are you’ll also want to define it’s width, any margins or padding, and anything else you want to be different in that specific area of your site. Here’s what my site’s content DIV style looks like:

div#content
{
        width: 640px;
        float: left;
        margin: 0 0 0 51px;
        padding: 0 18px 0 0px;
}

 

 

 

As you can see, it has a width of 640px. It also floats to the left, just like we talked about earlier. Additionally, I’ve added a 51px margin on the left side and 18px of padding on the right side. How do I know which numbers correspond to which sides? In CSS margins and padding code, it goes like this: top, right, bottom, left. This is easy to remember because, abbreviated, it looks like TRBL. That sounds like trouble or terrible when you sound it out. Either way, that’s a quick and easy way to remember it.

Header

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

The header is a fun part of your page to style because you get to decide how the menus look. Although you might have additional elements in your header should you decide to add a few new things do the header.php file in your theme, menus are still the main draw. Menu items are given in a list style that, without styling, would look a lot like this:

  • Page One
  • Page Two
  • Page Three
  • Page Four
  • Page Five

The dots wouldn’t be green, but you’d basically end up with a list. You don’t want that, and presumably you want the menu running along the top of the page. We handled that problem for you and styled the menu so it appears as one straight line of options rather than an unordered list. There are two pieces of CSS that make this happen. The first belongs to the .menu class’ ul (unordered list) element:

.menu ul
{
    list-style: none;
    margin: 0;
}

 

 

 

This code takes away the dots and any margin adjustments you’d get with an unordered list by default. The second relevant code block looks like this:

.menu li
{
    display: inline;
    float: left;
    padding: 0 8px 0 4px;
}

 

 

 

This code tells the list to display inline, which means it’ll display in a line rather than in a traditional list. Additionally, each list item (li) is told to float left (which will give us a little more freedom to move each item around) and have 8px of padding on the right and 4px of padding on the left (so the text isn’t so scrunched together. All of that’s enough to get you a basic menu, but we also want to style the a element (a as in a href, the link tag) to make all the links in the menu look the way we want. For that, we need this CSS:

.menu-item a
{
        font-size: 30px;
        text-decoration: none;
        color: #3eaf00;
}
.menu-item a:hover
{
        color: #5d8a05;
}

 

 

 

All this code does is set the font size (to 30px), the color of the font to green (specifically #3eaf00), and remove the underline that appears under links by default (text-decoration: none). The hover state just specifies a slightly darker green (#5d8a05) to display when the user rolls over any menu link. This is all pretty straightforward, basic CSS but it allows you to make your menu look different from the other text on your page without resorting to images. If you want to change the text even more, you can consider a different font or converting everything to upper or lowercase text. If you need some good web font options, you can find hundreds in the Google Web Font Directory.

Once you’ve made these style choices you’re pretty much done styling the menu and your header. There are definitely other styles you can find and play around with, but we’ll discuss how to locate those at the end of the post.

Content: Posts and Pages

Remember the div#content style we defined earlier? Pretty much everything in this and the following two content sections of this post relate to styles that exist just inside that DIV. Most of the

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

.entry-title
This is a style that relates to different page headers. In the styles.css file, you’ll find it attached to h1s, h2s, and h3s most often. Post headers adopt the .entry-title style regardless of what h# tag they are, so you can define each individually by first specifying the h# tag and then adding .entry-title to it. You can see this in several pre-defined code blocks in your styles.css file, such as h1.entry-title and h2.entry-title. Static page titles work in the same way, but their style is .page-title and they generally only use the h1 tag along with that style. That means you shouldn’t need to define any header styles for page titles beyond h1.page-title. Styling these titles are just like styling any other text, but you want them to be big. If they’re as small as other text they won’t stand out like they should.

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

.alignright and .alignleft
These two styles simply align images to the left and right of an entry (and you can probably guess which is which). You’ll also notice that in your styles.css file, padding is applied to three sides of the image but not one. Why? The side with no padding is the side that won’t be next to text. This is the right side of the image on right-aligned images and the left side on left-aligned images. This is done so the image doesn’t look awkwardly indented in a block of text wrapping around it. When you’re creating your WordPress posts and pages and adding images to them, you’ll be able to choose the image’s alignment within the editor. These styles will automatically be applied to any aligned image in your post. Unless you want to increase/decrease the padding, or add additional styles, you can leave these two classes alone.

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

.entry-content
The entry-content style is applied to the contents of blog posts and static pages you create in WordPress. This class pretty much applies its styles to any text, images, or whatever end up in the body of the content you create. For the most part, you don’t have to do much here. You can set the text styles you want, decide what headers (h1, h2, h3, etc.) look like, style lists, and basically any other element you want to have a specific style in the content section.

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

.entry-utility
The entry utility is an class for a small section at the end of each post that provides context. It’ll offer up information like the post’s categories and tags, as well as an RSS feed. If you’re not just a reader but rather a writer on your WordPress site, you will also see an “Edit” link in this section. Adding style to .entry-utility will determine how this section looks.

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

.entry-meta
It’s easy to confuse entry-meta with entry-utility, but it’s different. It contains the author name, date, and other metadata. If you want to change the way it looks, such as make the text smaller since it isn’t vital information, you’ll want to edit this class.

.navigation
Navigation is a class for styling the navigation links at the bottom of your theme. Navigation links are the links that point to older and newer posts.

Content: Comments

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

Although the comments section might seemlike an easy styling task, it’s actually one of the most complex sections of the blog. The comment form, itself, is pretty straightforward, but as people reply to comments and then reply to those replies, you end up with a lot of nested comments. There is also plenty of metadata, as well as an avatar, the shows up alongside a user’s comment. This means you’ve got plenty of elements to style.

.comments
Primarily, there are three: h3, ol, li, and img. Of course, h3 refers to the comment header. Because comments are posted in an ordered list, the ol (ordered list) and li (list item) elements are necessary. In most cases you’ll want to borrow a few styles from your header menu because you won’t actually want numbers next to your comments. You may also want to change the background color of each comment in the list or add other styles as well. You can do that by styling the ol and li elements of the .comments class. Finally, styling the img element is important because comments will contain an avatar for the user. That avatar might be blank or generic, but it’ll still show up for every commenter. Styling the img tag in the comments class (.comments img) will provide you control over how those avatars look and how they behave when paired with the comment text.

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND1

.comment
Very similarly named to the previous class, .comment is the style that applies to specific comments.

.children
Children is the class used to target replies to comments. These replies are considered children of the comment. Replies to the replies are also considered children.

div#respond
The respond DIV is the DIV holding the comment reply form. If someone wants to leave a comment, they’ll need to use this form to do so. You’ll want to style this DIV in order to make the form look the way you want. For the most part you’ll just be changing text, but you can also style form elements and buttons for an especially unique look.

Content: Sidebar

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

Styling the sidebar is actually pretty easy, but it can get more complex if you want to get very specific. WordPress gives you two widget areas: div#primary and div#primary. You can target each of those DIVs individually, or you can add styles to both of them using the .widget-area class. Furthermore, each widget you add to a widget area is added as—surprise!—a list item. The .xoxo class is applied to this list and can be used to separate and style each widget the way you want. If you want to get really specific, however, you’ll need to target each widget directly. We’ll discuss how to do that in the next section.

Additional Styles

How to Create a Custom Theme for Your WordPress Blog with Minimal Coding RequiredEXPAND

Now that we’ve talked about all the basic styles you’ll need to target in order to turn this blank theme into your own, let’s discuss how you can take it a bit further. WordPress themes containtons of elements so there are undoubtedly more you’ll want to style. In order to easily discover what they are as you’re going through the development process, all you need is the right tool.

If you’re using Chrome, that development tool is built right in. Just preview your theme as you’re developing it and open up the Developer Tools. You can do that by going to the View menu and choosing Developer -> Developer Tools. In Firefox (and many other browsers), justdownload and install Firebug, then click on the Firebug extension to activate it. Whichever tool you use, it’ll cause the screen to split into top and bottom halves. The top half will contain the page and the bottom half will contain the pages code. If you mouse over any element on the page you’ll see it highlighted in the code so you can inspect further. This will quickly tell you what the element is called and show you any styles already applied to it. You can then use this knowledge to add a new style for that element (or the class applied to it). Just continue doing that until you’ve found all the styles you want to add to your styles.css file. When you’re finished, you’ll have a completed theme!

Ref: lifehacker.com

Cake PHP Tutorial Day-2

Posted: July 20, 2014 in Uncategorized

<< Go to Cake PHP Tutorial Day-1 Part-1
<< Go to Cake PHP Tutorial Day-1 Part-2

Day-2:

Hopefully, you have created all tables in the database. Now, we are going to create Models, Views and Controllers.

1. Create Model files at tut/app/Model
2. All Model classes, we are going to create should extended from class “AppModel”
1


4
5
6
3
2

 

3.  Now, lets start creating Controllers & Views for each section of our application.

Formats:

To begin we need to create a new controller file called FormatsController.php and place this in the controllers directory.

Generally a Controller takes care of all the business logic of the application with each method inside the file taking care of an action that the system does.

For example each method inside a controller corresponds to a URL of the system, if a user visits localhost/admin/formats/add then the logic inside the admin_add() method of the Formats Controller would be processed. This makes it very easy to organise and maintain your code and is one of the main benefits of using the MVC software pattern.

When creating a new controller I like to code all of the methods I’m likely to use and for the Formats Controller I will need the following:

For User:

  • index()
  • view()

For Admin:

  • admin_index()
  • admin_add()
  • admin_edit()
  • admin_delete()

12

Next, we need to create new View files called index.ctp and admin_index.ctp in the/app/View/Formats/ folder. The views files are pretty basic and will output the formats in a table.

Note: .ctp indicated CakePHP Template

To access, you can browse localhost\tut\admin\formats\index or localhost\tut\admin\formats
This will execute admin_index() function in the controller and the view “admin_index.ctp” will be called.
Before browsing, open app\Config\core.php and uncomment line No: 152 as shown below;
a1

Now, browse  localhost\tut\admin\formats\index
14
Note:
If your list shows empty, then do not worry. Because, you have no records in “formats” table yet.

 

CakePHP tutorial Day-1 Part-2

Posted: July 19, 2014 in Uncategorized

<<Go to CakePHP tutorial Day-1 Part-1

Day-1  (Part-2) : 

Before starting the project, you should understand about Model, View and Controller in a brief. You can refer book.cakephp.org further for more details.

Model:

Models are the classes that form the business layer in your application. They should be responsible for managing almost everything regarding your data, its validity, and its interactions, as well as the evolution of the information workflow in your domain. We are going to put all our models at “/app/Model” folder.

Controller:

After routing has been applied and the correct controller has been found, your controller’s action is called. You will understand this when we start the project. We are going to put all our models at “/app/Controller” folder.

View:

The view layer of CakePHP is how you speak to your users.  It represents the HTML output on the screen. It refers what and how you are going to represent the output on the screen. We are going to put all our models at “/app/View” folder.
Project Brief:

I am going to develop one simple DVD management application with CakePHP.  For my DVD Catalog I want an application that will manage my ever growing collection of DVDs ( films and TV shows ). For each DVD that is entered into the application I want to add an image ( preferably a cover image ), a website URL, the Imdb website entry and a personal rating.

Along with being able to add / edit / delete DVDs I would like a front end display so that other people can go online and browse my collection as well. This front end will have search and filter functionality so that I can search by name or filter by format type etc. The front end also needs to be fully customisable so I’m going to implement a templating system where I can easily change the layout in the admin panel.

Note: Similar project is done in CakePHP1.2 by James   which is not working now in CakePHP 2.5.2.  I am going to make it more simple and develop with CakePHP 2.5.2

1. You have created database “tut”. Now let’s create tables. Before that, here is the understanding.

Good planning is paramount to any system so here are the requirements for the DVD Catalog Application:

  • Formats
    • These are the different formats of DVD that will exist in the system.
    • A few examples of format types include dvd, dvdcopy, dvdrip, tvrip and hd.
    • Be able to add / edit / delete format types.
    • Be able to sort and filter DVDs by format type.
  • Types
    • These are the different types of DVD in the system.
    • Examples include Films and TV Shows.
    • Be able to add / edit / delete types.
    • Be able to sort and filter DVDs by Type.
  • Locations
    • These are the different locations where your DVDs will be stored.
    • Examples include spindle 1, spindle 2, etc.
    • Be able to add / edit / delete locations.
    • Be able to sort and filter DVDs by Location.
  • DVDs
    • These are the actual DVDs that you will enter into the system.
    • Each DVD will have a number of attributes:
      • The Format Type, is it a DVD? a Copied DVD? A DVD Rip?.
      • The Type, is it a Film? Is it a TV Show?
      • The Location.
      • Name.
      • Image URL.
      • Official Website.
      • Imdb Link.
      • Rating.
      • Number of Discs.
      • Number of Episodes if its a TV Show.
  • Genres
    • A DVD will be able to belong to a number of genres.
    • A Genre will have multiple DVDs.
    • An Admin will be able to add /edit / delete Genres from the system
    • A user will be able to:
      • Filter by Genre.
      • Search by Genre.
  • Admin Section
    • The application will have a password protected admin area where a logged in admin will be able to interact with the system.
    • Admins can add / edit / delete:
      • Formats
      • Types
      • Locations
      • DVDs
      • Templates
  • Front End
    • The application will have a front end that will be viewable to anyone.
    • The main front end will show all the DVDs in the system.
    • The number of displayed DVDs will be limited and so pagination will be required.
    • A user will be able to filter the DVDs by:
      • Format
      • Type
      • Location
      • DVD Rating
    • A user will also be able to search for DVDs.
    • A user will be able to bookmark search and filters.
    • A user will be able to select different templates, changing the appearance of the system.
  • Templates
    • The system will be able to incorporate numerous templates.
    • A template will be added by the admin of the application
    • The template name will be used to identify images and css used by the template
    • A user will be able to select the template to change the design.

      Database Structure

      From the list of requirements I’ve come up with 8 different tables for the database which include Formats, Types, Locations, DVDS, Genres, Templates and Admins.

      • Formats
        • id, name, slug, description, created, modified, status
      • Types
        • id, name, slug, description, created, modified, status
      • Locations
        • id, name, slug, description, created, modified, status
      • DVDs
        • id, format_id, type_id, location_id, name, slug, image, website, imdb, rating, discs, episodes, created, modified, status
      • Genres
        • id, name, slug, created, modified, status
      • DVDS_Genres
        • id, dvd_id, genre_id
      • Templates
        • id, name, layout_name, description, image, created, modified, status
      • Admins
        • id, username, password, last_login, statusNow, let’s start creating tables under database “tut”


Using CakePHP conventions our database table names are all plural and our join table is the plural names of the two tables in alphabetical format. This ensures that CakePHP will automatically be able to connect to the database and create associated data with Cake’s inbuilt Automagic methods

Formats, Types and Locations have exactly the same database fields but I’ve not combined them into one table and used a flag to identify them because I wanted to seperate out the logic for each type and it also makes it easier to sort and filter by the different tables when our system is up and running. The model associations between these tables and the DVD table will also be easier to maintain and establish. A “slug” has been entered that will be used for user friendly URLs so instead of seeing “/formats/view/1” you will see “/formats/view/dvdrip”.

CREATE TABLE `formats` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`desc` TEXT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);
CREATE TABLE `types` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`desc` TEXT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);
CREATE TABLE `locations` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`desc` TEXT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);

 The DVD table will store all our information for each DVD and will also contain “foreign keys” that will link a DVD to a Format, Type and Location.

CREATE TABLE `dvds` (
`id` INT NOT NULL AUTO_INCREMENT ,
`format_id` INT NOT NULL ,
`type_id` INT NOT NULL ,
`location_id` INT NOT NULL ,
`name` VARCHAR( 100 ) NOT NULL ,
`slug` VARCHAR( 100 ) NOT NULL ,
`image` VARCHAR( 255 ) NOT NULL ,
`website` VARCHAR( 255 ) NOT NULL ,
`imdb` VARCHAR( 255 ) NOT NULL ,
`rating` TINYINT NOT NULL ,
`discs` TINYINT NOT NULL ,
`episodes` TINYINT NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);

The Genre table will contain the name of the Genre along with a slug for friendly URLs. A Join table will also be needed to link up Genres with DVDs, this will be displayed in much more detail in our model associations but this allows DVDs to have multiple Genres and to allow a Genre to have multiple DVDs.
CREATE TABLE `genres` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`slug` VARCHAR( 255 ) NOT NULL ,
`created` DATETIME NOT NULL ,
`modified` DATETIME NOT NULL ,
`status` TINYINT( 1 ) NOT NULL DEFAULT '1',
PRIMARY KEY ( `id` )
);

CREATE TABLE `dvds_genres` (
`id` INT NOT NULL AUTO_INCREMENT ,
`dvd_id` INT NOT NULL ,
`genre_id` INT NOT NULL ,
PRIMARY KEY ( `id` )
);

 The templates table will store all the information relatating to the template, the layout name will be used to choose the images that the template will use along with the css file that will change the look and appearence of the front end system.

CREATE TABLE `templates` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  `layout_name` varchar(100) NOT NULL,
  `description` text NOT NULL,
  `image` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`id`)
);

The final table (admins) will be used to store the username and password of any user that has access to the admin area of the application.
CREATE TABLE `admins` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `last_login` datetime NOT NULL,
  `status` tinyint(1) NOT NULL default '1',
  PRIMARY KEY  (`id`)
);

So, Now, you have created all tables. Right ?  Take a break, may be by having a coffee.

<<Go to CakePHP tutorial Day-1 Part-1

Day-1 (Part-1):

I am getting many requests from students and PHP Programmers for an easy CakePHP Tutorial with step by step demonstration. I also have searched various sources, but unfortunately, CakePHP itself  lacks demonstrations and also, the existing tutorials are outdated with CakePHP 1.2.  Here is a tutorial demonstrating a small Project with CakePHP 2.5.2. On every saturday/sunday, I am able to update the blog as getting very less time to do this.

1. Download cakephp from cakephp.org   version 2.5.2 (Stable)
2. Keep it at root (For me it is C://wamp/www/)
3. Create a folder “tut” with in “www” (let “tut” refers  “tutorial”)
4. Extract all files of CakePHP zip file to “tut” folder as shown below.
1

5. Now run the project. For me it is; localhost:81/tut
6. The page will display as below.
2
7. Open app/Config/core.php in any editor. (I am using Dreamweaver). Go to line number 225 and change the Security.salt to any alphanumeric string.  Now, go to Line Number 230 and change the Security.CipherSeed to any number as shown below.
Note: You can use this website to generate strong security salt.
3
8. Create a database “tut“. Again, I request you to use the naming convention as I am using. Once you do this project, you can manipulate and keep your research.

9. Rename app/config/database.php.default to database.php and open it in the editor.
4
5

10. Go to line number 65 and change the database-login id, database-password and database name. For me, it is like;
611. Now browse your project in the browser. For me, it is http://localhost:81/tut.  It will be like;
7
12. Now, We are ready to start our project.

You can comment if felt any difficulty in any step. You can comment in this post or can mail me at deb882003@gmail.com
I may take some to reply (with in 24 Hours), as per my busy schedules.

Day-1 (Part-2) >>

.NET programmer urgently required to work at Bangkok;

1. VISA, Shading & Fooding to be provided by the company
2. Must have 2+ years of experience in .NET
3. Salary: Negotiable
4. No consultancy, No security
5. If interested, send resume to deb882003@gmail.com