U bent hier

WordPress Plugin Development for Designers – Custom Post Types

afbeelding van globecom

Hello Everyone! Welcome back to the third part of this series on WordPress Plugin development for designers.

In the first part we identified the importance of WordPress plugins for you as designers and the basic structure of a plugin. Then we followed it up with the necessary coding required for developing plugins in the second part, by creating a jQuery slider for WordPress.

I am happy to announce that SlidesJS has won the voting contest and I’ll be using it through the rest of this tutorial series.

I hope you have used the slider plugin and tried to fix the responsive issue we had in the demo. We got good responses containing the possible solutions. So we are going to start the third part by fixing the responsive issue in the slider.

Download Slider Version 2 | Demo

Following is an image from demo we created in the previous part, illustrating the responsive issue.

wpdd_part3_1

Making SlidesJS Responsive

SlidesJS is designed to use 940px as its default width. Most of the websites are designed in a grid with at least 960px width. So default SlidesJS slider will be responsive in full width pages. We are using the TwentyEleven theme in this demo. It doesn’t offer the full width in its default pages or posts. Therefore we have to adjust the slider according to our themes to make it responsive.

CSS media queries can be used effectively to make the slider responsive. So let’s take a look at the default media queries provided by SlidesJS.

960px layouts will fit into the media query between 768px and 979px. Slider container is defined as 724px for that particular width range. Basically what you have to do is adjusting the width of slider container based on your themes content area dimensions. So the updated media queries to suit TwentyEleven theme are as follows.

You can see that I have modified the widths of all the media queries to suit TwentyElevan theme container sizes. Now let’s look at the slider after the code updates. Make sure to add these styles for media queries into the example.css file in the plugin.

wpdd_part3_2

We have completed the responsive version of static slider for WordPress. But it’s useless until we enable the capabilities for adding images dynamically through the WordPress dashboard. So let’s get started on making dynamic sliders.

Planning the Dynamic Slider Functions

In the current version of the plugin, we are using the images inside the plugin folder. But we want to put our own images in an user friendly method. Also we should be able to create multiple sliders for different locations of our web sites. Let’s list down the functionality we need to implement in this part.

  • Create multiple sliders
  • Upload images dynamically through WordPress media uploader.
  • Assign and remove images of sliders at any given time

Implementing these functionalities is not a very difficult task for people who are knowledgeable in working with PHP. But as designers you might find it a little difficult to understand if you have zero background about PHP. So I am going to explain things as simple as possible to make it easy for you.

Also keep in mind that you don’t need to understand each and every detail discussed here. I’ll tell you the tasks you need to focus and tasks you can omit as designers. So stay tuned and get ready with your code editor.

Creating Slider – Role of Custom Post Type

Most of you will be familiar in working with WordPress posts. Even if you haven’t developed or designed anything on WordPress, there is a high possibility that you have wrote an article on a WordPress blog. WordPress posts are designed to write article, tutorials or some content for your website. Following image displays the post creation screen of WordPress.

wpdd_part3_3

Usually we get fields like post title, post content, categories, featured image to insert necessary data for specific posts. Similarly WordPress provides a technique called Custom Post Types. Basically custom post type can be considered as a special kind of post. We can use custom post types to create some amazing designs and features to WordPress. In this part we are going to use specific custom post type to create sliders.

Most important thing to keep in mind is that custom post types doesn’t show in the normal post section and hence will not get displayed on your blog. We have the capability to create unique designs for these post types and decide where we should display them.

Creating Slider Post Type

I assume that you have already installed and activated the previous version of the plugin we developed in the last part. Here I’ll be adding and modifying the existing codes of the plugin.

First we have to register a new post type for sliders. You can insert the following code into the end of the 1wd_slider.php file of the plugin.

add_action('init', 'fwds_register_slider');

function fwds_register_slider() {

$labels = array(

'menu_name' => _x('Sliders', 'slidesjs_slider'),

);

$args = array(

'labels' => $labels,

'hierarchical' => true,

'description' => 'Slideshows',

'supports' => array('title', 'editor'),

'public' => true,

'show_ui' => true,

'show_in_menu' => true,

'show_in_nav_menus' => true,

'publicly_queryable' => true,

'exclude_from_search' => false,

'has_archive' => true,

'query_var' => true,

'can_export' => true,

'rewrite' => true,

'capability_type' => 'post'

);

register_post_type('slidesjs_slider', $args);

}

WordPress executes an action called init in its initialization process of a user request. We can call any function on the init action. Here I have used a function called fwds_register_slider.

Inside the function we have to define some labels and parameters for custom post types. Labels will decide the text displayed on menu items and forms. There is a bunch of arguments to configure various features of a custom post type. Finally we register the custom post type using the register_post_type function. First parameter to this function will be the name of the custom type. You can use any unique name for that. Next we pass the arguments as the second parameter.

Understanding the complete code and configurations is not necessary at this stage as a beginner in WordPress. Following is a preview of the custom post type section for Sliders once we include this code.

wpdd_part3_4

As you can see, there is a separate section for Slider posts on the left menu and the label is converted into the text we used in the labels variable.

Things to Focus

  • Whenever you want to create Sliders, Accordions, Tabs or similar design components, use the following block of code with a new function name for init action.
  • In the labels section, change the text you want to appear and the unique post type name according to your preference.
  • Keep the arguments variable as it is now and don’t worry about the various parameters used there for the moment.
  • Finally use the same unique name used in the labels array for the register_post_type function.

Each time you use this code with different function and unique post type, new section will be added to the left menu. Now try to use Sliders in the dashboard.

We can use this section to create sliders. But still it works as normal post type and won’t do anything different. Our next task is to add images into sliders. Let’s move forward.

Creating Slider Image Fields

We have to insert different images to each new slider. WordPress meta boxes can be used effectively to add additional fields to the slider creation screen. Consider the following code.

add_action('add_meta_boxes', 'fwds_slider_meta_box');

function fwds_slider_meta_box() {

add_meta_box("fwds-slider-images", "Slider Images", 'fwds_view_slider_images_box', "slidesjs_slider", "normal");

}

function fwds_view_slider_images_box() {
global $post;

$gallery_images = get_post_meta($post->ID, "_fwds_gallery_images", true);
// print_r($gallery_images);exit;
$gallery_images = ($gallery_images != '') ? json_decode($gallery_images) : array();

// Use nonce for verification
$html = '';

$html .= '
'; $html .= "

";

echo $html;

}

First we have to call a new function on add_meta_boxes action to create a meta box for our sliders. Inside the function we define a new meta box using the add_meta_box function as shown in the following code.

function fwds_slider_meta_box() {

add_meta_box("fwds-slider-images", "Slider Images", 'fwds_view_slider_images_box', "slidesjs_slider", "normal");

}

First parameter is a unique key for meta box followed by meta box title. Third parameter is a new function to execute the meta boxes. Fourth parameter is the unique post type we created earlier and you can leave the final parameter to its default value of normal.

Then we need to create the fwds_view_slider_images_box function to implement the meta box.Inside the function we get the available image values for the current slider from the database. We can save images of each slider into database with slider id and a key (_fwds_gallery_images).

In the initial loading, there wont be any existing images and hence the gallery images will be empty. Then we create the fields for the images using HTML codes. I have used 5 text boxes here to enter 5 images for each slider.

Now your slider creation screen should look like the following image.

wpdd_part3_5

Things to Focus

  • Create add_meta_box functions and load it with respective parameters. If you are creating 2 types of sliders, use 2 add_meta_box functions.
  • Create new function like fwds_view_slider_images_box for each of the sliders you want to use.
  • I have used 5 images per slider. Add or remove text boxes according to your preference to get more or less images per slider.

Uploading Images to Slider

Now we can start uploading images to the slider. Just click the Add Media button on the Slider creation screen to load the WordPress media uploader. Then upload images as you do for normal posts. You should get a screen like the following once an image is uploaded.

wpdd_part3_6

In the link to section on the right, you can select whether to use the image as an attachment or media file. Select media file to get the direct link to the uploaded image. Now copy the link and close the upload window. Then insert the copied image url into the Image 1 field we created earlier. Continue this process for all the slides you want to appear in the slider.

Once all the links are filled, your slider creation screen will look like the following.

wpdd_part3_7

Saving Slider Images

We have uploaded and inserted the images into the slider. Now images need to be saved to the database. Even though image fields are in the slider creation screen, it won’t be saved automatically when the post is saved. We have to use a simple code to insert the data into the database as shown below.

add_action('save_post', 'fwds_save_slider_info');

function fwds_save_slider_info($post_id) {

// verify nonce

if (!wp_verify_nonce($_POST['fwds_slider_box_nonce'], basename(__FILE__))) {

return $post_id;

}

// check autosave

if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {

return $post_id;

}

// check permissions

if ('slidesjs_slider' == $_POST['post_type'] && current_user_can('edit_post', $post_id)) {

/* Save Slider Images */

//echo "
";print_r($_POST['gallery_img']);exit;

$gallery_images = (isset($_POST['gallery_img']) ? $_POST['gallery_img'] : '');

$gallery_images = strip_tags(json_encode($gallery_images));

update_post_meta($post_id, "_fwds_gallery_images", $gallery_images);

} else {

return $post_id;

}

}

We call a custom function on save_post action to save the image details to the database. update_post_meta function is used to save these details into the _fwds_gallery_images key. I’ll show you the things you need to know in this section as it might be little complex for the beginners in design.

Things to Focus

  • When you are saving different types of posts like sliders, accordions,tabs, make sure to create new function on save_post action and use this block of code.
  • Inside the check permission section, use your own post type instead of slidesjs_slider.
  • Use your own unique key like _fwds_gallery_images to save the data into the database.

Now when the slider is published, all the images will be saved to the database. Then click on the Sliders section from the left menu and you will get a list shown in the following image.

wpdd_part3_8

You will be able to see a separate shortocde in front of each slider you create. You can use these to generate sliders once we complete the following section.

Generating Slider Using Uploaded Section

In the previous part we used a shortcode function to include images to the slider as shown in the following code.

add_shortcode("1wd_slider", "fwds_display_slider");
function fwds_display_slider() {

$plugins_url = plugins_url();

echo '




';
}

As you can see all the images are hard coded in this version. Now we have the option of using dynamic sliders as well as dynamic images. So let’s move into implementing the shortcode.

add_shortcode("1wd_slider", "fwds_display_slider");

function fwds_display_slider($attr,$content) {

extract(shortcode_atts(array(

'id' => ''

), $attr));

$gallery_images = get_post_meta($id, "_fwds_gallery_images", true);

$gallery_images = ($gallery_images != '') ? json_decode($gallery_images) : array();

$plugins_url = plugins_url();

$html = '

';

foreach ($gallery_images as $gal_img) {

if($gal_img != ""){

$html .= "";

}

}

$html .= '

';

return $html;

}

Now we use the post ID passed to the shortcodes to retrieve the images dynamically. Then we assign each image to the slider using a foreach loop. Finally we return the resulted slider to be displayed inside our pages.

Things to Focus

  • You can use get_post_meta function with specific key to load any kind of details saved in the database.
  • We can pass any number of attributes to shortcode and you have to include them inside the extract function to retrieve the values.
  • Here we are getting image links from database. You can get and save any type of information using the get_post_meta function according to your shortcode type.

Now we have completed our slider plugin for this part and you can try creating sliders with different images. Once created, copy the shortwcode from the list and insert into a post or page to see it in action.

Following image shows the preview of our slider in the TwentyElevan theme.

wpdd_part3_9

Whats Next?

In this part we completed the slider functionality. Now its dynamic and effective to suit various types of sections in your web pages.

What about sizes, effects, speeds of sliders?

Definitely a plugin becomes much more user friendly and customizable when you have options to choose and settings to define it’s features. So in the next part we will be adding options to our slider to complete the initial part of this plugin development series.

By the end of next part you will be able to create basic WordPress plugins for UI components using the techniques discussed here. Until then I hope you will practice these theories with different sliders.

Can You Solve These?

In the previous part I asked you to fix the responsive issues in the slider. In this part I provided more questions to solve and learn. Try the following and let me know how it goes.

  • Can you insert options into slider and use it inside shortcodes?
  • SlidesJS slider does not play automatically. Can you find how it can be set to slide automatically?

Looking forward to your answers.

Wrap Up

In this part I was forced to omit explanations for each and every code line due to the complexity it can cause for you as web designers. Your focus should be on using this code and creating different types of sliders as well as other components without worrying too much about the complex codes.

By now you should be able to insert another type of slider into the same plugin with the instructions I gave on the Things to Focus sections.

Let me know how it goes and any help you need in making different sliders using this plugin.

Onze klanten

From the blog

afbeelding van globecom
afbeelding van globecom

Changing next number in a Drupal serial field

After searching for 2 days on Drupal.org without finding a good way to change the starting point of a serial field I

Read more...
afbeelding van globecom

Automatisch PDF maken, mailen en toevoegen als bijlage

Voor een klant had ik de uitdaging het volgende te maken.

Read more...

Neem contact op

  • Globecom
          Schoolstraat 245
          7606EM
          Almelo
  • +31 (0)634924795
  • info@globecom.nl

Laatste Tweets

Latest Shots