Category Archives: HTML

Understanding ARIA Click Button to Show or Hide Content Example Code

Understanding ARIA

ARIA stands for "Accessible Rich Internet Applications". Also known as the WAI-ARIA standard, it is a standard developed to help coders to provide proper semantics for custom widgets and to make them accessible, usable, and interoperable with assistive technologies for people with disabilities. To be clear, ARIA doesn't add functionality to an object. It adds roles and states that assist in identifying the intent and state of an object. However, usually JavaScript code is still needed to add any dynamic action to that object. I state this clearly at the top of this post because at first, I was under the impression that ARIA also added certain functionalities to HTML objects and was seriously disappointed when I found out otherwise. For example, when ARIA is used on a button that hides and shows content in a div, it only defines the roles and states of the button and corresponding div. JavaScript is still needed to do that work of hiding and showing the div in question.

Example Code

Here is an example of correctly implementing ARIA controls when making a button that hides and shows a div on the click of your mouse. It also binds the space bar and enter key to the div as well, so pressing either of those keys toggles the visibility of the div as well. Without any further ado, the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Aria Examples</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<style>
div.topic {
    display: none;
    margin-bottom: 1em;
    padding: .25em;
    border: black thin solid;
    background-color: #EEEEFF;
    width: 40em;
}
</style>
</head>
<body>

<p class="button">
    <button id="button1" class="buttonControl" aria-controls="t1" aria-expanded="false"><span>Show</span> Topic 1</button>
</p>

<div id="t1" class="topic" role="region" tabindex="-1" >
    Topic 1 is all about being Topic 1 and may or may not have anything to do with other topics.
</div>

<script>
$(document).ready(function() {

   var hs1 = new hideShow('button1');
  // var hs2 = new hideShow('button2');
  // var hs3 = new hideShow('button3');
  // var hs4 = new hideShow('button4');
 
}); // end ready()

//
// function hideShow() is the constructor for a hideShow widget. it accepts the html ID of
// an element to attach to.
//
// @param(id string) id is the html ID of the element to attach to
//
// @return N/A
//
function hideShow(id) {

   this.$id = $('#' + id);
   this.$region = $('#' + this.$id.attr('aria-controls'));

   this.keys = {
               enter: 13,
               space: 32
               };

   this.toggleSpeed = 100;

   // bind handlers
   this.bindHandlers();

} // end hidShow() constructor

//
// Function bindHandlers() is a member function to bind event handlers to the hideShow region
//
// return N/A
//
hideShow.prototype.bindHandlers = function() {

   var thisObj = this;

   this.$id.click(function(e) {

      thisObj.toggleRegion();

      e.stopPropagation();
      return false;
   });
}

//
// Function toggleRegion() is a member function to toggle the display of the hideShow region
//
// return N/A
//
hideShow.prototype.toggleRegion = function() {

      var thisObj = this;

    // toggle the region
    this.$region.slideToggle(this.toggleSpeed, function() {

      if ($(this).attr('aria-expanded') == 'false') { // region is collapsed

        // update the aria-expanded attribute of the region
        $(this).attr('aria-expanded', 'true');

        // move focus to the region
        $(this).focus();

        // update the button label
        thisObj.$id.find('span').html('Hide');

      }
      else { // region is expanded

        // update the aria-expanded attribute of the region
        $(this).attr('aria-expanded', 'false');

        // update the button label
        thisObj.$id.find('span').html('Show');
      }
    });

} // end toggleRegion()
</script>
</body>
</html>

Thank you oaa-accessibility.org for providing me with enough knowledge to create and use the above example! They have the best example code for ARIA usage that I could find online after many Google searches. See their complete list of example ARIA examples at http://oaa-accessibility.org/

ARIA and WordPress

I noticed ARIA controls for the first time in the header.php file for my WordPress theme. I was trying to fix a mobile navigation menu and thought couldn't find the code that makes the menu appear on mobile devices when the button is clicked and thought ARIA had something to do with it. I was basically wrong. ARIA code was only present to mark the navigation menu and make it's role and states readily accessible. It is after all an accessibility feature.

Summary

So ARIA and the WAI-ARIA standard are used to enable more accessible HTML markup for disabled people. While it is a great initiative, it doesn't add much dynamic functionality to your HTML objects, JavaScript is still needed for that. ARIA combined with HTML, CSS and JavaScript can be used to make accessible web pages more user-friendly.

How to Add Custom Fields to WordPress Navigation Menu Items

The task of adding custom fields to WordPress navigation menus has come up a few times in my work, so I figured I should document the process which I have learned since it is fairly complex and not very well documented on the internet to this date. Kudos to those of you who have figured this out and documented it because it is one of the more advanced tasks involving WordPress that I have had to do. I am not sure why WordPress made it so complex to alter the navigation menu infrastructure, but to be a true WordPress expert, you do need to learn to work with it, so I aim to help others learn, as I have, how to manipulate the WordPress navigation menus with as much ease as possible.

This is by far one of the more advanced tutorials for WordPress, so if you don't feel like going through all of the steps below. I've already made a plugin for this that will be for sale on my site. If you want to get an advance copy of it email me at linian11@yahoo.com and I can help you out.

Adding custom Fields to WordPress Navigation Menu Items

To be perfectly clear, here is a screenshot of the default menu editing screen after I made my initial top navigation menu for my site, Jafty.com with no added custom fields:

nav1

In contrast, here is the same screen under appearance/menus after I have added two custom fields to it using the methods I'll describe below:

nav2

Notice in the above image, the addition of the "Icon URL" and "Custom Field #2" fields. These I added with my custom plugin. Read on to find out how to add similar fields and how to access them or display them on the front-end of your site.

On the front-end, I added two icons to the menu real quick so you can see what it looks like:

iconnav

The above image is a sub nav that pops up when you click on "Projects" and I added icons to the first two sub-links using the new "icon URL" field added with the method I'm about to show you...

THE CODE:

So to accomplish this, I started a new plugin called "Jafty Top Nav". I made a folder named jafty-top-nav and a file inside it named jafty-top-nav.php with the following contents:

<?php
/**
* Plugin Name: Jafty Top Nav
* Plugin URI: http://jafty.com/
* Description: A Plugin that adds a custom top navigation menu to WordPress. This also adds the icon menu option to the WordPress admin, allowing one to select an icon to appear before submenu items in submenu dropdowns.
* Version: 1.0
* Author: Ian L. of Jafty.com
* Author URI: http://jafty.com
* License: GPL2
*/

//adds the Primary Jafty Menu location to wp-admin:
add_action('after_setup_theme', 'register_jafty_menu');
function register_jafty_menu(){
register_nav_menu('jafty-top-nav', __('Primary Jafty Menu', 'jafty-top-nav'));
}

//includes the library used to add custom fields to menu items:
require_once dirname( __FILE__ ) . '/menu-item-custom-fields/menu-item-custom-fields.php';

//include 'http://jafty.com/wp-content/plugins/jafty-top-nav-plugin/menu-item-custom-fields.php';
include 'menu-item-custom-fields.php';

class Jafty_Walker extends Walker_Nav_Menu {

// Displays start of an element. E.g '<li> Item Name'
// @see Walker::start_el()
function start_el(&$output, $item, $depth=0, $args=array(), $id = 0) {
$object = $item->object;
$type = $item->type;
$title = $item->title;
$description = $item->description;
$permalink = $item->url;
$icon = get_post_meta($item->ID, 'menu-item-icon-url', true);
$output .= "<li class='" .  implode(" ", $item->classes) . "'>";

//Add SPAN if no Permalink
if( $permalink && $permalink != '#' ) {
$output .= '<img src="'.$icon.'" style="width:25px;float:left;margin-right:10px;margin-top:3px" /><a href="' . $permalink . '">';
} else {
$output .= '<span>';
}

$output .= $title;
if( $description != '' && $depth == 0 ) {
$output .= '<small class="description">' . $description . '</small>';
}
if( $permalink && $permalink != '#' ) {
$output .= '</a>';
} else {
$output .= '</span>';
}
}
}

?>

The most important portion of code above I put in red text. That is where I retrieve one of the custom fields in order to display it in the nav menu. You will notice below that I named the field "icon-url" in the "jafty-custom-nav-fields.php" file and above I reference it with "menu-item-icon-url", so take notice of this so you don't cause an error.

Then I created a second file inside the same "jafty-top-nav-plugin" folder named "jafty-custom-nav-fields.php" which has the following code:

<?php
/**
* Custom menu items metadata:
*/
class Jafty_Custom_Nav_Fields {

/**
* Holds our custom fields
*/
protected static $fields = array();

/**
* Initialize plugin
*/
public static function init() {
add_action( 'wp_nav_menu_item_custom_fields', array( __CLASS__, '_fields' ), 10, 4 );
add_action( 'wp_update_nav_menu_item', array( __CLASS__, '_save' ), 10, 3 );
add_filter( 'manage_nav-menus_columns', array( __CLASS__, '_columns' ), 99 );

self::$fields = array(
//note that menu-item- gets prepended to field names
//i.e.: field-01 becomes menu-item-field-01
//i.e.: icon-url becomes menu-item-icon-url
'icon-url' => __( 'Icon URL:', 'jafty_custom_nav_fields' ),
'field-02' => __( 'Custom Field #2', 'jafty_custom_nav_fields' ),
);
}

/**
* Save custom field value
*
* @wp_hook action wp_update_nav_menu_item
*
* @param int   $menu_id         Nav menu ID
* @param int   $menu_item_db_id Menu item ID
* @param array $menu_item_args  Menu item data
*/
public static function _save( $menu_id, $menu_item_db_id, $menu_item_args ) {
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return;
}

check_admin_referer( 'update-nav_menu', 'update-nav-menu-nonce' );

foreach ( self::$fields as $_key => $label ) {
$key = sprintf( 'menu-item-%s', $_key );

// Sanitize
if ( ! empty( $_POST[ $key ][ $menu_item_db_id ] ) ) {
// Do some checks here...
$value = $_POST[ $key ][ $menu_item_db_id ];
} else {
$value = null;
}

// Update
if ( ! is_null( $value ) ) {
update_post_meta( $menu_item_db_id, $key, $value );
echo "key:$key<br />";
} else {
delete_post_meta( $menu_item_db_id, $key );
}
}
}

/**
* Print field
*
* @param object $item  Menu item data object.
* @param int    $depth  Depth of menu item. Used for padding.
* @param array  $args  Menu item args.
* @param int    $id    Nav menu ID.
*
* @return string Form fields
*/
public static function _fields( $id, $item, $depth, $args ) {
foreach ( self::$fields as $_key => $label ) :
$key   = sprintf( 'menu-item-%s', $_key );
$id    = sprintf( 'edit-%s-%s', $key, $item->ID );
$name  = sprintf( '%s[%s]', $key, $item->ID );
$value = get_post_meta( $item->ID, $key, true );
$class = sprintf( 'field-%s', $_key );
?>
<p class="description description-wide <?php echo esc_attr( $class ) ?>">
<?php printf(
'<label for="%1$s">%2$s<br /><input type="text" id="%1$s" class="widefat %1$s" name="%3$s" value="%4$s" /></label>',
esc_attr( $id ),
esc_html( $label ),
esc_attr( $name ),
esc_attr( $value )
) ?>
</p>
<?php
endforeach;
}

/**
* Add our fields to the screen options toggle
*
* @param array $columns Menu item columns
* @return array
*/
public static function _columns( $columns ) {
$columns = array_merge( $columns, self::$fields );

return $columns;
}
}
Jafty_Custom_Nav_Fields::init();
?>

The most important part of the above code is the field names. I changed the text color for the field names to red. However you also need to be aware that you have to append "menu-icon-url" to the field names when you go to fetch them in your header.php theme file later on so icon-url would become icon-url-menu-icon-url" for example...see the note above the code as well.

Then I used two files created by  Dzikri Aziz and put them in their own folder named "menu-item-custom-fields" inside of the jafty-top-nav folder. Here are the names and content of those two files if you are copy and pasting as we go:

menu-item-custom-fields.php content:

<?php

/**
 * Menu Item Custom Fields
 */

if ( ! class_exists( 'Menu_Item_Custom_Fields' ) ) :
    /**
    * Menu Item Custom Fields Loader
    */
    class Menu_Item_Custom_Fields {

        /**
        * Add filter
        *
        * @wp_hook action wp_loaded
        */
        public static function load() {
            add_filter( 'wp_edit_nav_menu_walker', array( __CLASS__, '_filter_walker' ), 99 );
        }

        /**
        * Replace default menu editor walker with ours
        *
        * We don't actually replace the default walker. We're still using it and
        * only injecting some HTMLs.
        *
        * @since   0.1.0
        * @access  private
        * @wp_hook filter wp_edit_nav_menu_walker
        * @param   string $walker Walker class name
        * @return  string Walker class name
        */
        public static function _filter_walker( $walker ) {
            $walker = 'Menu_Item_Custom_Fields_Walker';
            if ( ! class_exists( $walker ) ) {
                require_once dirname( __FILE__ ) . '/walker-nav-menu-edit.php';
            }

            return $walker;
        }
    }
    add_action( 'wp_loaded', array( 'Menu_Item_Custom_Fields', 'load' ), 9 );
endif; // class_exists( 'Menu_Item_Custom_Fields' )

// Uncomment the following line to test this plugin
#require_once dirname( __FILE__ ) . '/doc/menu-item-custom-fields-example.php';

walker-nav-menu-edit.php content:

<?php

/**
 * Custom Walker for Nav Menu Editor
 *
 */
class Menu_Item_Custom_Fields_Walker extends Walker_Nav_Menu_Edit {

    /**
     * Start the element output.
     *
     * We're injecting our custom fields after the div.submitbox
     *
     * @see Walker_Nav_Menu::start_el()
     * @since 0.1.0
     * @since 0.2.0 Update regex pattern to support WordPress 4.7's markup.
     *
     * @param string $output Passed by reference. Used to append additional content.
     * @param object $item   Menu item data object.
     * @param int    $depth  Depth of menu item. Used for padding.
     * @param array  $args   Menu item args.
     * @param int    $id     Nav menu ID.
     */
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $item_output = '';

        parent::start_el( $item_output, $item, $depth, $args, $id );

        $output .= preg_replace(
            // NOTE: Check this regex from time to time!
            '/(?=<(fieldset|p)[^>]+class="[^"]*field-move)/',
            $this->get_fields( $item, $depth, $args ),
            $item_output
        );
    }

    /**
     * Get custom fields
     *
     * @access protected
     * @since 0.1.0
     * @uses add_action() Calls 'menu_item_custom_fields' hook
     *
     * @param object $item   Menu item data object.
     * @param int    $depth  Depth of menu item. Used for padding.
     * @param array  $args   Menu item args.
     * @param int    $id     Nav menu ID.
     *
     * @return string Form fields
     */
    protected function get_fields( $item, $depth, $args = array(), $id = 0 ) {
        ob_start();

        /**
         * Get menu item custom fields from plugins/themes
         *
         * @since 0.1.0
         * @since 1.0.0 Pass correct parameters.
         *
         * @param int    $item_id  Menu item ID.
         * @param object $item     Menu item data object.
         * @param int    $depth    Depth of menu item. Used for padding.
         * @param array  $args     Menu item args.
         * @param int    $id       Nav menu ID.
         *
         * @return string Custom fields HTML.
         */
        do_action( 'wp_nav_menu_item_custom_fields', $item->ID, $item, $depth, $args, $id );

        return ob_get_clean();
    }
}

Then finally, the last thing you have to do is edit your header.php file for your current WordPress theme to include something like this where your to site navigation code appears:

<nav id="site-navigation" class="main-navigation" role="navigation">
            <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Jafty Menu', 'jafty-theme' ); ?></button>
            <?php wp_nav_menu( array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-jafty-menu', 'walker' => new Jafty_Walker() ) ); ?>
        </nav><!-- #site-navigation -->

Summary

That's all there is to it. I know it's a lot, but if you start out by copy and pasting my code and following instructions carefully to recreate the above jafty-top-nav plugin, it should work fine. Afterwards, you can edit it to fit your own personal requirements as needed. Good luck!

 

I want to give credit for the help I got on this technique, but frankly I saw the same code in different areas online and don't know which is the correct site to link to, but in one of the files, the author gave his name, which was Dzikri Aziz, so I'd like to extend my thanks to Dzikri Aziz for helping me bring this code to life. If I find a link I'll post it or if anyone knows it, please comment and I'll make sure he gets the appropriate credit for his portion of the code I used in this article.

Get the Nth Weekday of Any Month and Year with JavaScript

In today's challenge for a client of mine, I had to write a JavaScript function that returns the Nth Weekday of any given month and year. For example it can tell you what the 1st Monday is in December, 2017. It can do past, present and future so if you needed to know the 4th Friday in August of 1910, this function can tell you. If you need to know what the second Sunday of January 2050 is going to be, this JavaScript function will tell you!

Without any further time wasting, here is the JavaScript code that can determine the first, second, third, fourth or even fifth Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday for any month and year you pass it:

JavaScript Code Returns Nth Weekday for any Given Month & Year:

<script>
/* JavaScript getMonthlyWeekday Function:
 * Written by Ian L. of Jafty.com
 *
 * Description:
 * Gets Nth weekday for given month/year. For example, it can give you the date of the first monday in January, 2017 or it could give you the third Friday of June, 1999. Can get up to the fifth weekday of any given month, but will return FALSE if there is no fifth day in the given month/year.
 *
 *
 * Parameters:
 *    n = 1-5 for first, second, third, fourth or fifth weekday of the month
 *    d = full spelled out weekday Monday-Friday
 *    m = Full spelled out month like June
 *    y = Four digit representation of the year like 2017
 *
 * Return Values:
 * returns 1-31 for the date of the queried month/year that the nth weekday falls on.
 * returns false if there isn't an nth weekday in the queried month/year
*/
function getMonthlyWeekday(n,d,m,y){
var targetDay, curDay=0, i=1, seekDay;
    if(d=="Sunday") seekDay = 0;
    if(d=="Monday") seekDay = 1;
    if(d=="Tuesday") seekDay = 2;
    if(d=="Wednesday") seekDay = 3;
    if(d=="Thursday") seekDay = 4;
    if(d=="Friday") seekDay = 5;
    if(d=="Saturday") seekDay = 6;
while(curDay < n && i < 31){
    targetDay = new Date(i++ + " "+m+" "+y);
    if(targetDay.getDay()==seekDay) curDay++;
}
if(curDay==n){
targetDay = targetDay.getDate();
return targetDay;
}else{return false;}
}//end getMonthlyWeekday JS function
</script>
<a href="JavaScript:var dy = getMonthlyWeekday(1,'Sunday','March', 2017);alert('1st Sunday in March, 2017 falls on March, '+dy);">Get first sunday in March, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(2,'Sunday','March', 2017);alert('2nd Sunday in March, 2017 falls on March, '+dy);">Get second sunday in March, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(5,'Sunday','March', 2017);alert('5th Sunday in March, 2017 falls on March, '+dy);">Get fifth sunday in March, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(4,'Friday','April', 2017);alert('4th Friday in April, 2017 falls on April, '+dy);">Get 4th Friday in April, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(5,'Monday','April', 2017);alert('5th Monday in April, 2017 falls on April, '+dy);">Get 5th Monday in April, 2017</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(3,'Wednesday','October', 1995);alert('3rd Wednesday in October, 1995 falls on October, '+dy);">Get 3rd Wednesday in October, 1995</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(4,'Wednesday','October', 1995);alert('4th Wednesday in October, 1995 falls on October, '+dy);">Get 4th Wednesday in October, 1995</a><br />
<a href="JavaScript:var dy = getMonthlyWeekday(4,'Wednesday','May', 1975);alert('4rd Wednesday in May, 1975 falls on May, '+dy);">Get 4th Wednesday in May, 1975</a><br />

Summary

That will do the job! All you have to do is copy and paste the above code in green into a blank text file and name it something like weekdays.html or test.html and open it in any web browser to test the code. Then feel free to alter it to fit your exact needs. Have fun!

 

 

 

Including Responsive Videos in WordPress Posts

I've done a lot of things with WordPress to-date, but one thing I haven't done much with is videos. I was commissioned to build a plugin to embed responsive videos into WordPress posts. Naturally I started trying to figure out how to embed a simple Vimeo video into a post, this post right here in fact. I went to Vimeo.com and got the link for one of the videos my client is using. I am going to post just that plain text link on the next line below:

...and presto-magico! WordPress did most of the work for me! As you can see the video showed up just from me copy and pasting the Vimeo URL in the post! For example, I posted "https:// vimeo.com/ 155235235" without the quotes or spaces. I just added spaces so WordPress wouldn't make it a video like it did above.

Therefore, the only task left to me is to make the videos responsive.

How to make videos responsive in WordPress

The most basic method, which you may want to use if you only need to apply this fix to one or two videos on your site,  is to add a wrapper div to your video url when you insert it int o your blog post like this:

<div class="video-wrap"> VIDEO URL GOES HERE! </div>

Then add the following CSS to your theme's main style sheet, style.css:

.video-wrap{
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
}
.video-wrap iframe, .video-wrap object, .video-wrap embed, .video-wrap video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

That's all you have to do if you don't mind making manual edits each time you add a video to your blog.

Making a Simple WordPress Plugin to Make Videos Responsive

The logical option to use if you regularly embed videos in your WordPress site, is to create a very simple plugin that hooks into WordPress while it embeds videos and automatically wraps the embed code inside of a div and then applies style to that div to accomplish the same effect we did above without having to make changes each time we add a new video. Here is how:

Add the following code to a new php file and name it whatever you want to call your custom plugin or call it jafty-responsive-video-embedder as I did here:

<?php
/*
Plugin Name: Jafty Responsive Video Embedder
Plugin URI: http://jafty.com

Description: Adds a wrapper div around embedded videos and applies mobile style to them so they are responsive at all times regardless of the surrounding HTML.

Author: Ian L. of Jafty.com
Author URI: http://jafty.com

Version: 1.0.0

License: GNU General Public License v2.0
License URI: http://www.opensource.org/licenses/gpl-license.php
*/

//Code to make Videos more responsive:
function make_video_responsive( $html ) {
    return '<div class="video-wrap">' . $html . '</div>';
}
 
add_filter( 'embed_oembed_html', 'make_video_responsive', 10, 3 );
add_filter( 'video_embed_html', 'make_video_responsive' ); // Jetpack

function add_video_css(){
wp_enqueue_style("videocss", "/wp-content/plugins/outer-gain-engine/video.css");
}

add_action('wp_enqueue_scripts', 'add_video_css');

?>

Then create a file named video.css and copy and paste the follocing CSS code into it:

.video-wrap{
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
}
.video-wrap iframe, .video-wrap object, .video-wrap embed, .video-wrap video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Summary

That's all there is to it. A simple, yet handy, plugin or fix for your WordPress videos. Feel free to modify the code to fit your individual needs. Good Luck!

How to Use jQuery UI Elements In a WordPress Plugin or Theme

Today I found myself once again needing to use jQuery in a new WordPress plugin I am developing for a client. I won't lie, I often dread having to use jQuery within WordPress. It has been getting easier however, especially since WordPress version 3.3.x when they made many of the jQuery UI libraries part of the WordPress core. The trick is knowing that and knowing how to use them! For example I didn't know about the jQuery UI libraries being part of the WP core until recently, so was just hacking my own jQuery into WordPress. The problem with hacking in a jQuery UI or any other jQuery code, is that it will usually break some other jQuery code in WordPress. Therefore I am putting together a quick reference guide on how to include jQuery and jQuery UI scripts in WordPress plugins and themes for my own reference and for other developers who can profit from this information.

First, here is a list of 35 jQueryUI elements already available within WordPress as of version 3.3.x:

Name: Enqueue Value: Dependency:
jQuery UI Core jquery-ui-core jquery
jQuery UI Widget jquery-ui-widget jquery
jQuery UI Accordion jquery-ui-accordion jquery
jQuery UI Autocomplete jquery-ui-autocomplete jquery
jQuery UI Button jquery-ui-button jquery
jQuery UI Datepicker jquery-ui-datepicker jquery
jQuery UI Dialog jquery-ui-dialog jquery
jQuery UI Draggable jquery-ui-draggable jquery
jQuery UI Droppable jquery-ui-droppable jquery
jQuery UI Menu jquery-ui-menu jquery
jQuery UI Mouse jquery-ui-mouse jquery
jQuery UI Position jquery-ui-position jquery
jQuery UI Progressbar jquery-ui-progressbar jquery
jQuery UI Selectable jquery-ui-selectable jquery
jQuery UI Resizable jquery-ui-resizable jquery
jQuery UI Selectmenu jquery-ui-selectmenu jquery
jQuery UI Sortable jquery-ui-sortable jquery
jQuery UI Slider jquery-ui-slider jquery
jQuery UI Spinner jquery-ui-spinner jquery
jQuery UI Tooltips jquery-ui-tooltip jquery
jQuery UI Tabs jquery-ui-tabs jquery
jQuery UI Effects jquery-effects-core jquery
jQuery UI Effects – Blind jquery-effects-blind jquery-effects-core
jQuery UI Effects – Bounce jquery-effects-bounce jquery-effects-core
jQuery UI Effects – Clip jquery-effects-clip jquery-effects-core
jQuery UI Effects – Drop jquery-effects-drop jquery-effects-core
jQuery UI Effects – Explode jquery-effects-explode jquery-effects-core
jQuery UI Effects – Fade jquery-effects-fade jquery-effects-core
jQuery UI Effects – Fold jquery-effects-fold jquery-effects-core
jQuery UI Effects – Highlight jquery-effects-highlight jquery-effects-core
jQuery UI Effects – Pulsate jquery-effects-pulsate jquery-effects-core
jQuery UI Effects – Scale jquery-effects-scale jquery-effects-core
jQuery UI Effects – Shake jquery-effects-shake jquery-effects-core
jQuery UI Effects – Slide jquery-effects-slide jquery-effects-core
jQuery UI Effects – Transfer jquery-effects-transfer jquery-effects-core

As you can see in the above table, the first 22 items in the list only require jQuery as a dependency. For those, you probably will only need to enqueue the value from the "Enqueue Value" column to make use of the library in your plugin or theme. You often will need to enqueue style for the jQuery library separately as well because as far as I know, WordPress doesn't include many of the styles yet. the last dozen or so in the above table all require jquery-effects-core, so to use those, I believe you'll need to enqueue that as well for them to work. For a complete list of other jQuery scripts that are already within the WordPress core, please visit the following codex page:

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

That page also explains usage of the wp-enqueue-script function to  a degree, but not as detailed as my special-use case described here.

How to Enqueue jQuery UI Elements in WordPress Plugin or Theme

Next I'm explaining how to include a jQuery UI library into your own WordPress plugin or theme. If you're making a plugin, the code below will go into your plugin's main file and if you're working on a theme, then place the code below in the theme's functions.php file. In the following code examples, I'll demonstrate how to include both the jQuery UI element and the corresponding CSS file for using a datepicker in both the front-end and admin areas of WordPress. The code would be the same for any of the UI elements in the above table except that you would of course change the valuse to be enqueued for both the core jQuery file and the CSS file from googleapis.com.

PHP Code to use jQuery UI on the WordPress Front-End

function my_datepicker_function(){
//Enqueue date picker UI from WP core:
wp_enqueue_script('jquery-ui-datepicker');
//Enqueue the jQuery UI theme css file from google:
wp_enqueue_style('e2b-admin-ui-css','http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css',false,"1.9.0",false);
}
add_action('wp_enqueue_scripts', 'my_datepicker_function');

How to add PHP Code to Use jQuery UI on the WordPress Admin or Back-End

The PHP code to include the same datepicker UI in a WordPress back-end, admin page is nearly the same. The only difference is the hook we use in the add_action line at the end of the code is different. For front-end use, we used the wp_enqueue_scripts hook, but for admin use, we will use the admin_enqueue_scripts hook instead. That's all folks!

Then simply include your HTML and  script tag wherever you want to use your datepicker in this case like so:

<div class="wrap">
<input type="text" class="datepicker" name="datepicker" value=""/>
</div>

<script>
jQuery(function() {
    jQuery( ".datepicker" ).datepicker({
        dateFormat : "dd-mm-yy"
    });
});
</script>

Summary

the above example code is just for datepicker UI, but can easily be manipulated for any of the jQuery UI elements in the above table, so experiment and find the one that works for you. You will often need to google the jQuery UI element's name and view an online demo of how it is used without WordPress to get exact code and then simply incorporate the above technique into what you learn. I did this with the sortable UI and it worked great. Good luck!

 

How to Do Something Every Nth Iteration in a PHP Loop

If you're a PHP coder, you are sure to come across a scenario from time to time where you have a PHP loop and you need to execute specific code every other time the loop iterates or every four times the loop iterates etc.

Using the Modulus Operator

The key to making something happen every nth time in a loop is the modulus operator or %.

A common scenario where you would need to do something in a loop every fourth or fifth iteration only is when you are printing a series of HTML elements. Let's pretend we have 12 items in an array and we want to print them in groups of four per line. While printing the array you will need to print the <br /> tag every four iterations if you want four items on each line.  The code inside your PHP loop would look like this:

if($i % 4 == 0){echo "<br />";}

Now let's put this to the test with some test code using the above scenario. Below I fill an array with 12 words and print them out in a loop four per line:

<?php
$words = array('one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve');
$noof = count($words);
$i=0;
for($ii=0;$ii<$noof;$ii++){
    $i++;
    echo $words[$ii];
    echo " ";
    if($i % 4 == 0){echo "<br />";}
}//end for loop
?>

Noticed I used $ii in the for loop and set a second variable, $i for using with the modulus line. This is because $ii will start at zero and we need to start at 1 in this case. The results of the above code would be:

one two three four
five six seven eight
nine ten eleven twelve

Today however, I came across a more complex scenario where I was able to also use the modulus operator to save the day. This time I needed to print items from an array inside of HTML list elements. Lets modify the above scenario using lists instead of line breaks to display the array data:

<?php
$words = array('one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve');
$noof = count($words);
$i=0;
for($ii=0;$ii<$noof;$ii++){
    $i++;
    if($i % 4 == 1)echo "<ul>";
    echo "<li>";
    echo $words[$ii];
    echo "</li>";
    if($i % 4 == 0)echo "</ul>";
}//end for loop
?>

The output of the above PHP code would be:

  1. one
  2. two
  3. three
  4. four
  1. five
  2. six
  3. seven
  4. eight
  1. nine
  2. ten
  3. eleven
  4. twelve

 

The results were four separate ordered lists  as you can see. But how did we do this? Notice the difference in the modulus operator use for the opening <ol> tag and then for the closing </ol> tag.

The tricky part here is we can't use if($i % 4 == 0) on the opening <ol> tag because if you think about it you don't need <ol> printed on 4,8 and 12 which is what if($i % 4 == 0) would produce. In this case, we need to print an opening <ol> tag on iterations 1,5,9 and 13, so we try something else. Here is how I figured this problem out:

First a simple demo of the modulus operator as we first used it:

<?php
$i=0;
for($ii=0;$ii<20;$ii++){
    $i++;
    if($i % 4 == 0)echo "$i<br />";
}//end for loop
?>

The above code results in:

4
8
12
16
20

Which is fine for printing the end </ol> tags, but will not work for printing the opening <ol> tags as I explained earlier, so I tried this instead:

<?php
$i=0;
for($ii=0;$ii<20;$ii++){
    $i++;
    if($i % 4 == 1)echo "$i<br />";
}//end for loop
?>

This time the above code printed out:

1
5
9
13
17

So, if we used a one instead of a zero like if($i % 4 == 1), then it would execute the code in the if statement on iterations 1,5,9 and 13 just as we need! Just for fun, let's see what happens if we use a two instead of zero this time like if($i % 4 == 2). For example:

<?php
$i=0;
for($ii=0;$ii<20;$ii++){
    $i++;
    if($i % 4 == 2)echo "$i<br />";
}//end for loop
?>

This time the results would be:

2
6
10
14
18

so using a 2 to compare 4 modulus with results in the code executing on iterations 2,6,10....etc, but notice in each example where we use 4 as the first number, all the numbers are increments of 4 and when we use zero as the last number we get 4,8,12.... When we use 1 we get 1,5,9.... Finally if we use 2 we get 2,6,10.... From what we have learned I think it's safe to assume that we we used 3, the results would be 3,7,11,15....and so on.

Summary

I hope this article sheds some light on how to use the Modulus operator with PHP. Feel free to experiment by using other numbers in place of where I used 4 each time too! For example, if you want to do something every 5 times instead, you would use something like if($i % 5 == 0). Have fun with it!

 

Building a Custom WordPress Navigation Menu Plugin

This is a semi-advanced WordPress tutorial so you should have a little bit of existing knowledge of WordPress if you want to be able to understand the concepts involved. I will try to make it as easy to follow as possible none-the-less.

We are just going to dive right in a create a new Plugin. I'll be calling the plugin Jafty-Nav, you can follow suit if you wish to keep things simple or give it your own name if you feel comfortable making such changes.

Create a New Plugin

<?php
/**
* Plugin Name: Jafty Top Nav Plugin
* Plugin URI: http://jafty.com/blog/?p=9813
* Description: A Plugin that adds a custom top navigation menu to WordPress.
* Version: 1.0
* Author: Ian L. of Jafty.com
* Author URI: http://jafty.com
* License: GPL2
*/

Register a New Menu Location with WordPress

Add this PHP code to your plugin file you created above:

<?php
add_action('after_setup_theme', 'register_jafty_menu');
function register_jafty_menu(){
  register_nav_menu('jafty-top-nav', __('Primary Jafty Menu', 'jafty-top-nav-plugin'));
}
?>

Now that is actually enough to create a simple plugin. The plugin will add a menu location to wp-admin and that's it, but we'll build on it after we install it. So go ahead and install the plugin by putting it into a folder named "jafty-top-nav-plugin" and naming the file "index.php". Then upload to your WordPress plugins directory. Activate the Jafty Top Nav Plugin then go to your admin and click on "Appearance/Menus" then select the "Manage Locations" tab and you'll see the new menu location your plugin as added to the admin like in the image below.

menuLOC

Placing a new top nav in your theme

The next task is to edit your current WordPress theme to work with the Jafty Top Nav Plugin. You'll need to create a new header file and edit your page, post and/or home page templates to contain your new top navigation menu. Here is how:

  1. Go into your current theme's folder and download a copy of the header.php file to your desktop and rename it header-jafty.php.
  2. open header-jafty.php in notepad and find the section that looks something like this:<nav id="site-navigation" class="main-navigation" role="navigation">
    <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', 'outer-gain-dev' ); ?></button>
    <?php wp_nav_menu( array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-menu' ) ); ?>
    </nav>
  3. Inside the code within the Nav tag in your header-jafty.php file, change the theme_location value to 'jafty-top-nav' and save the file.
  4. Now upload your header-jafty.php file to your active theme's folder.
  5. Next you'll want to add the new header to your template files, Some templates you might want to do this too are front-page.php, single.php, page.php and any custom page templates in your theme or child theme you might have. The process is very similar for adding the new header to any of the files, so I'll just demonstrate on the home page template file, front-page.php. Open the template file in your notepad and near the top of the code you should see something like this:
    get_header();
    or you may have something like this instead:
    get_template_part('templates/header.php');
    Regardless which you have, replace the line with:
    get_header('jafty');
    and that will call your new header.jafty.php template into the page template so your customized header will be shown.
  6. Save and upload your altered template file and repeat for all necessary page and post templates until you have your new top nav menu at the top of all desired pages and/or posts throughout your entire WordPress site.

Now that we have more control of it, let's customize that ugly top nav!

Customizing the WP Navigation Menu

It's time to get down and dirty with some real-world customization of the top navigation menu in WordPress. We are not just doing some simple CSS changes here, we are talking about a complete rewrite of the navigation system. This is why I went with a plugin for this. Now I had to find what WordPress core functions I could use to alter the menu completely. My goal is to make a menu similar to the one at Stripe.com, which is not a WordPress site by the way. I just love the dynamic drop downs that fade in and out and their use of icons in the sub-menu items. I'll get to how I duplicated all of that later on, first we need to know how to rebuild the entire menu structure because the stripe.com style menu is nothing like a standard WordPress menu. Here's what I figured out:

 

First we need to be able to retrieve our custom navigation links from the WordPress backend. Remember earlier we created a menu location? Well, we need to retrieve the menu assigned to that particular location in WordPress. Therefore the first thing we want to do is make sure there is a menu assigned to the "Primary Jafty Menu". You could pick one from the drop down, but we want to make a new one that is sure to have both main menu items and sub menu items so we can adequately test our menu when it's complete. Therefore we locate the "Primary Jafty Menu" and click the link to the right of it that reads "Use New Menu" as I've circled in red in the below image:

menuLOC2

When creating the new Primary Jafty Menu, give it a name of "Jafty 1". It's best to do everything exactly as I have done just to be sure you don't have any conflicts. You can always change names and such after you have a completed working plugin. When creating the menu, make sure to add at least 2 main menu items with at least 2 sub menu items each so we can test the drop down effects. Here is an image of the one I made for testing. If you don't have enough pages or posts to make that many links, don't worry, just use two real links for the main menu items and click on "custom links" and create outside links for all of your sub menu items as I have done in the below image:

menustructure

In the above image, "site settings" and "Hello world!" represent our two main menu items and the sub links rest below them indented to show their sub-link status. Notice I have "Primary Jafty Menu" checked under "Menu Setings" too. Once you have your menu, be sure you save it. Now we can return to developing our plugin!

Retrieve Menu and Sub Menu Items from WordPress Admin

It is time to develop some custom WordPress code to extract out menu items and sub-menu items from the database. Lucky for us, WordPress has some built-in core functions to assist us. Here is the code I come up with to extract all menu and sub-menu items for the "Jafty Primary Menu" from the database to display them on the front-end:

<?php
      $menuLocations = get_nav_menu_locations(); // Get nav locations
      $menuID = $menuLocations['jafty-top-nav']; //menu assigned to Jafty Primary Menu
      $theNav = wp_get_nav_menu_items($menuID);
                
                    foreach ($theNav as $navItem) {
                        //get the url for the link:
                        $navURL = $navItem->url;
                        //get the nav link text/title:
                        $navTXT = $navItem->title;
                        //Get the nav link's ID:
                        $navID = $navItem->ID;
                        //Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
                        $navParent  = $navItem->menu_item_parent;
                        echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
                    //echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
                    }
 ?>

The above code will go in out header file named header-jafty.php. Lets examine the code so you understand what it does.

The first line:

$menuLocations = get_nav_menu_locations(); // Get nav locations

as the comment says afterwards, it gets the navigation menu locations stored in WordPress. We added one of these in the beginning of the tutorial using the register_nav_menu function.

The second line reads:

$menuID = $menuLocations['jafty-top-nav']; //menu assigned to 'Primary Jafty Menu'

This line fetches the ID of the menu currently assigned to the menu location we created in the plugin file, "Primary Jafty Menu". We then use the id in the next line that reads:

$theNav = wp_get_nav_menu_items($menuID);

We now have a WordPress menu object stored in $theNav. If you do a print_r($theNav) command in PHP, you would see that the menu object holds all sorts of information about the menu we created earlier. However, we only need four key pieces of information from the menu object. We need to get:

  1. The Link URL
  2. The Link Text
  3. The Link ID
  4. The Link's Parent ID in case it is a sub-menu item.

We can get the four pieces of information we need using a foreach loop on the $theNav object like so:

     foreach ($theNav as $navItem) {
                        //get the url for the link:
                        $navURL = $navItem->url;
                        //get the nav link text/title:
                        $navTXT = $navItem->title;
                        //Get the nav link's ID:
                        $navID = $navItem->ID;
                        //Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
                        $navParent  = $navItem->menu_item_parent;
                        echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
                    //echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
                    }

We now have all the information we need about the menu items after running the above foreach loop on the menu object. We have the link text, URL, ID and Parent ID. It's important to note that the parent ID will always be 0 if the link is a main menu item and we can determine if the link is a sub-menu item if the parent ID is anything other than zero. Then we know which link to put the sub-link under by matching the sub-link's parent ID to the ID of the main link item. Pretty simply really, once you get accustomed to it.

Now we need to open our header-jafty.php file and find the line that reads something similar to:

<?php wp_nav_menu( array( 'theme_location' => 'jafty-top-nav', 'menu_id' => 'primary-menu' ) ); ?>

And replace it with the code we wrote above:

<?php
$menuLocations = get_nav_menu_locations(); // Get nav locations
$menuID = $menuLocations['jafty-top-nav']; // Get the *primary* menu ID
$theNav = wp_get_nav_menu_items($menuID);

foreach ($theNav as $navItem) {
//get the url for the link:
$navURL = $navItem->url;
//get the nav link text/title:
$navTXT = $navItem->title;
//Get the nav link's ID:
$navID = $navItem->ID;
//Get menu item parent(will be 0 if main link or parent ID if it's a sub link):
$navParent  = $navItem->menu_item_parent;
echo "ID: $navID, $navTXT, $navParent, $navURL<br />";
//echo '<li class="has-dropdown gallery" data-content="about"><a href="'.$navURL.'" title="'.$navItem->title.'">'.$navTXT.'</a></li>';
}
?>

Now save your header-jafty.php file and upload it to your active theme's folder and refresh your home page. You should see the following information printed in the header area of your site instead of a top nav now:

ID: 47, Site Settings, 0, http://dev.outergain.com/site-settings/
ID: 49, Jafty Interactive, 47, http://jafty.com
ID: 50, Jafty Blog, 47, http://jafty.com/blog
ID: 48, Hello world!, 0, http://dev.outergain.com/2016/12/30/hello-world/
ID: 51, Yahoo Search, 48, http://yahoo.com
ID: 52, Google Search, 48, http://google.com

As you can see my site returned 6 lines of text in the header, one for each of the two main menu items and one for each of the four sub-menu items in the menu I created in wp-admin. Each of the lines above contains the main ID first, followed by the link text, then the parent ID and finally the link text. I highlighted the parent IDs in blue so you can see how the two main menu items have a parent ID of zero while the other four have parent IDs equal to the two main menu items with zero for parent ID. Make sense? I hope so:-)

For all you professional WordPress plugin developers, I can probably stop there. Now you have enough to make your own custom top navigation menu for your WordPress theme. You clearly don't need to do this as a plugin, in fact, it would normally done by adding the plugin code to functions.php in the current theme instead. I am making it a plugin just as a learning exercise.

You can use the information it printed in your header to figure out how to add in the HTML and CSS for any type of custom nav you desire, or you can read on to see how I recreated the stripe.com-like top nav for one of my clients.

Make a Static Top Navigation Menu as a Demo

Before we go about coding the menu into WordPress, I like to create a static version first. I created mine based on looking at the top nav found on Stripe.com. You can click the link to see what I mean. I didn't copy it by any means, but I did use it as a model for creating a similar one with similar transition effects. In the static demo, I didn't create great detail in the drop downs. Instead I concentrated on getting the transition effects and infrastructure perfect. I can worry about making the content of the dropdown boxes look pretty when I code it into the actual WordPress site. Here is my static demo: http://jafty.com/nav_demo

I won't post all of the code to my static navigation menu demo here but you may feel free to use the link provided and use your browser's view source option to see how I made it and copy it if you so desire.

 

 

 

The WordPress Loop

Today I finally decided to dedicate a single tutorial on the wonderful WordPress loop. I will demonstrate how to create a basic loop and show several examples of the loop in action. The loop is what gets post and/or page data in WordPress template files, so if you ever have a need to make a custom page or post template, you'll need to understand how the loop works.

 

The Basic WordPress Loop

Most often you will see the loop look something like this:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<!------------This is where you present your post data....-------------->

<?php endwhile; else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

The above example doesn't contain the middle part of the loop in order to demonstrate where the loop typically begins and ends. That way you can find the loop in your current theme and work with it by knowing where it starts and stops at least.  Next we'll discuss what to put in between where it says <!------------This is where you present your post data....-------------->.

Fetching Data Inside a WordPress Loop

Post Title:

First I'll show you how to display the Title as a link to the Post's permalink.

<h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

Just place the above code example where it says you present your post data in the the loop example above.

Post Content:

You can display the Post's content in a div with the following code inside of your loop:

<div class="entry">
<?php the_content(); ?>
</div>

Again, use the above code in between the starting and ending loop code explained above and this will display the general content of the post as entered into the standard WYSIWYG editor in the WordPress admin.

Using More Than One Loop

If you need to use two more more loops in the same template file, then you will have to reset the WordPress loop with rewind posts function like this:

<?php rewind_posts(); ?>

Just use the above line before your second loop and any loops afterwards and they will reset and be ready to function again.

 

Cron Job Not Working

Cron jobs seem to be one of the things I have to do often that give me trouble. That's why I'm putting together this guide full of troubleshooting tips for people having problems with cron jobs.

Just today, for example, I wasted several hours figuring out why my cron job didn't seem to be working and here is what happened:

I set up my cron job exactly as I always do according to my own tutorial I posted here:

Linux Cron Job Tutorial

however, it didn't seem to be working so I tried chaing the shebang, changing the php location, etc. with no luck at all.

The Solution

Finally after hours of wasting time, I figured out that the output of my cron job was not going where I thought it would go. For example, my test script created a file and wrote a line to that file to show the cron job ran. My cron test PHP file looked like this:

crontest.php:

<?php

#!/usr/bin/php
<?php
$myFile = "cronresults.txt";
$fh2 = fopen($myFile, 'a') or die("can't open file to append");
$stringData = "appended text from cron job...\n";
fwrite($fh2, $stringData);
fclose($fh2);
?>

Simple, right? well the trick is the $myFile variable works as expected in that it creates the file in the same directory as crontest.php when crontest is called from a web browser. So when I opened up Firefox and went to mysite.com/crontest.php, it worked fine, it would create a file named cronresults.txt in my public_html folder and write a simple line of text to it. However. HERE IS THE TRICKY PART! I call the script in crontest.php from a cron tab by adding the following line in crontab -e:

* * * * * /usr/bin/php   /var/www/mysite.com/public_html/crontest.php

but when I call it that way and look for the cronresults.txt file or look for the line of text it added to the file if it already exists, there is nothing so it appears as if the cron job didn't work! Oh damn! I say. Then I try everything I can think of to fix it. The problem is that is was never broken! When you call a PHP script from a cron job and you do not specify the file path of the results file, it assumes the current users home folder! Therefore, it was working the whole time, but was creating and writing to a file in my /home/root directory because that's the directory I called crontab -e from! THerefore my solution was as simply as replacing the $myFile line with this:

$myFile = "/var/www/mysite.com/public_html/cronresults.txt";

WHEN YOU USE THE ENTIRE PATH IT WORKS AS EXPECTED! I can't over emphasize the importance of this because I wasited several hours due to not knowing this.

Cron Job Troubleshooting Tips

  • Always use a simple test script to test cron jobs for the first time on a new server. You can use my example crontest.php script above, but be careful to set the $myFile variable with the entire path to the output file or you'll have the same problem I wrote about above in this post.
  • Always use a very simple command line in crontab when first testing your cron job. You can customize it after you get it working. I use something like:                               * * * * *  /usr/bin/php  /path/to/cron/crontest.php      then crontest.php will be executed every minute so you can quickly see if it is working. This makes testing and debugging much easier.
  • Can't figure out your Shebang or don't know where PHP is on your server? Then simply go to a command prompt on your server using putty remotely or any command prompt if you are on your own server and type the following command: "which php" without the quotes. That will give you the path to php for both your shebang and your crontab file, like where it says /usr/bin/php in my examples above.

Working with WordPress Advanced Custom Fields Image Repeater Fields

My latest WordPress project deals with remote updating of custom post types that use the Advanced Custom Fields Plugin. From here on out, I'll simply refer to this plugin as ACF since it is such a long name and ACF is the generally accepted name among WordPress developers...

I am writing this post mostly because when working with ACF and repeater fields that have a sub field type of image, I wasn't able to find sufficient documentation on the subject to complete my project. I did complete the project with a lot of trial and error and piecing together of bits of info from many sources. My goal is to document the subject as much as possible here in order to make life easier for anyone attempting to do similar tasks as I have done.

The Challenge:

My particular challenge was that I had to create a WordPress plugin that would sync posts that used a custom post type and ACF. The basic requirement was that the plugin would update several client sites with posts from a single master site. So, the master site had a custom post type named "farms" that had several ACF fields including a couple repeater fields, one of which used the "image" sub-field type which is the focus of this article. The main challenge for me was basically writing code to insert images into a post that used a repeater field that had two sub-fields(image and alt_tag) the image sub-field stored image data in an array and the alt_tag sub-field stored custom alt tag content for the image tag. Some of you might already be thinking: Why do you have an alt_tag sub-field when alt tag content is already stored in the image data array. Well, that is true. However, it was a requirement of the project, so that's what I did.

 

The solution:

How to add WordPress Advanced Custom Fields(ACF) Image Repeater Fields with PHP Code

Today's challenge is to add values to an ACF image repeater field from within a plugin or theme file using PHP code. I had a difficult time figuring this out myself due to not being able to find enough documentation on the subject, so I decided to document my findings here. I used a custom post type named "farms" with my example. You can use a regular post, page or any custom post type for your own project. Just note that wherever you see "farms" it is my custom post type and should be replaced with your own value.

Export one or more of the posts in question

A logical first step to solving this problem for me was to create an XML export file of one of the posts that I wanted to add repeater field values to. in order to accomplish this, first create a test post of the custom post type you will be working with and make sure that the repeater field is all set up using the ACF plugin. Be sure to add a minimum of two images under the repeater field so you can examine the data via the XML export file. See the image below for an example of my own test custom post type which was set up with proper data to export:

post

Now it's time to export the post you just edited. To do this from wp-admin, click on "tools/export" and select the name of your custom post type. In my case, I select "farms" and click to export the posts as in the following image:

export

Open your XML file you downloaded and search for the post by title. Once you find the title, you could extract just that one post's data by copying everything in between <item> and </item> and pasting it in a new  XML file. That makes it easier to read just the one post you are concerned with if you have a lot of posts and a long XML file to work with. Of course, this is an optional step. I have extracted my relevant post and also deleted some of the XML that wasn't relevant to the task and here are the results:

<item>
...
<wp:postmeta>
<wp:meta_key><![CDATA[your_own_farm_pics]]></wp:meta_key>
<wp:meta_value><![CDATA[2]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[_your_own_farm_pics]]></wp:meta_key>
<wp:meta_value><![CDATA[field_57ab934d407ed]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[your_own_farm_pics_0_image]]></wp:meta_key>
<wp:meta_value><![CDATA[1862]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[_your_own_farm_pics_0_image]]></wp:meta_key>
<wp:meta_value><![CDATA[field_57ab934d407ee]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[your_own_farm_pics_0_alt_tag]]></wp:meta_key>
<wp:meta_value><![CDATA[first alt tag]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[_your_own_farm_pics_0_alt_tag]]></wp:meta_key>
<wp:meta_value><![CDATA[field_57ab934d407ef]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[your_own_farm_pics_1_image]]></wp:meta_key>
<wp:meta_value><![CDATA[1861]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[_your_own_farm_pics_1_image]]></wp:meta_key>
<wp:meta_value><![CDATA[field_57ab934d407ee]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[your_own_farm_pics_1_alt_tag]]></wp:meta_key>
<wp:meta_value><![CDATA[second alt tag]]></wp:meta_value>
</wp:postmeta>
<wp:postmeta>
<wp:meta_key><![CDATA[_your_own_farm_pics_1_alt_tag]]></wp:meta_key>
<wp:meta_value><![CDATA[field_57ab934d407ef]]></wp:meta_value>
</wp:postmeta>
</item>

Once you've located your post's XML, you will want to find the portion that is relevant to your particular ACF repeater field. To do this, simply do a search for the repeater field slug name. My field was named "your own farm pics", so the slug name I would search for would be "your_own_farm_pics". The first instance you find of the repeater field name/slug will look something like this:

<wp:postmeta>
<wp:meta_key><![CDATA[your_own_farm_pics]]></wp:meta_key>
<wp:meta_value><![CDATA[2]]></wp:meta_value>
</wp:postmeta>

Due to the use of CDATA , the above may look a little more complex than it really is. For what we are doing, we can simply ignore all of the CDATA stuff so that the above would become more like this:

<wp:postmeta>
<wp:meta_key>your_own_farm_pics</wp:meta_key>
<wp:meta_value>2</wp:meta_value>
</wp:postmeta>

Basically what's in between the XML tags is this:
<![CDATA[your_own_farm_pics]]>
The part you want is in between the opening and closing brackets after the word, CDATA. The rest can be ignored. In this case, all we want is: your_own_farm_pics.

Then, to show one more example of extractig data from CDATA, the next line looks like:
<wp:meta_value><![CDATA[2]]></wp:meta_value>
and the only part we want is the part after "CDATA[", which is simply: 2

So examining the first poroption of relevent .xml code we can gather that the value of "your_own_farm_pics" is "2".

Lets look at the next portion of XML that reads:
<wp:postmeta>
<wp:meta_key><![CDATA[_your_own_farm_pics]]></wp:meta_key>
<wp:meta_value><![CDATA[field_57ab934d407ed]]></wp:meta_value>
</wp:postmeta>
...okay, from what we've learned, this is what you should extract from the above XML:
field name(or key): _your_own_farm_pics
value: field_57ab934d407ed
I hope this part is clear to you. If it is not, then you'll probably need to study an XML tutorial first to understand. But one thing you need to notice here is that the field name or key starts with an underscore, therefore it is different from the first meta key(_your_own_farm_pics instead of your_own_farm_pics).

Let's go ahead and extract all of the relevant data from the .xml file. Basically you should be able to extract something similar to the following key/value pairs from the relevant portion of XML code:

your_own_farm_pics
2

_your_own_farm_pics
field_57ab934d407ed

your_own_farm_pics_0_image
1862

_your_own_farm_pics_0_image
field_57ab934d407ee

your_own_farm_pics_0_alt_tag
first alt tag

_your_own_farm_pics_0_alt_tag
field_57ab934d407ef

your_own_farm_pics_1_image
1861

_your_own_farm_pics_1_image
field_57ab934d407ee

your_own_farm_pics_1_alt_tag
second alt tag

_your_own_farm_pics_1_alt_tag
field_57ab934d407ef

As you can see there are 4 pieces of data for each image in the repeater field. This is because there are two sub-fields in this repeater field and each sub-field uses two key/value pairs. Notice the incremented numbers starting at 0. There is only a 0 and a 1 in this example because there are two images stored in our repeater field. so all the key names containing _0_ are one image's data and then all the ones with key names containing _1_ are the second image's data.

There are three parts to each key name. Each key either starts with the repeater slug or the repeater slug preceded by an underscore. Then there is a incremented number starting at zero. Finally we have the sub-field name. Here's the pattern these sub-field key names follow:

repeater_field_name + incremented number + sub-field name

Above is the pattern for the data key. Below is the very similar patter for the field key:

underscore + repeater_field_name + incremented number + sub-field name

So knowing that, you should be able to know exactly how to read these XML files now. This also gives you a huge clue on how data is stored in the database as the key/value pairs in the XML file are exactly what is stored in the database. Therefore the values are exactly what needs to be written to the database in order to insert repeater images into a post or custom post type.

Let's examine some PHP code now. Knowing what we do about the XML file, we know what data needs inserted into the database now, so our PHP code for the example XML file above should look like this in order to insert two images into a repeater field for a single post:

Note that the below code is for adding two sets of repeater field values. The repeater field is set up with two sub fields, one image sub-field and one simple text sub-field named alt_tag.

<?php

$post_id = "1902";
//first two key/value pairs are for the repeater field name:
$key = "your_own_farm_pics";
$value = "2";
add_post_meta($post_id, $key, $value);

$key = "_your_own_farm_pics";
$value = "field_57ab934d407ee";
add_post_meta($post_id, $key, $value);

//next eight key/value pairs are for the two repeater field sub-field names:
//There are four key/value pairs for the first image and four more for the second:
//Start image one data:
$key = "your_own_farm_pics_0_image";
$value = "1867";
add_post_meta($post_id, $key, $value);

$key = "_your_own_farm_pics_0_image";
$value = "field_57ab934d407ee";
add_post_meta($post_id, $key, $value);

$key = "your_own_farm_pics_0_alt_tag";
$value = "Alt tag content for image 1";
add_post_meta($post_id, $key, $value);

$key = "_your_own_farm_pics_0_alt_tag";
$value = "field_57ab934d407ef";
add_post_meta($post_id, $key, $value);

//Start image two data:
$key = "your_own_farm_pics_1_image";
$value = "1869";
add_post_meta($post_id, $key, $value);

$key = "_your_own_farm_pics_1_image";
$value = "field_57ab934d407ee";
add_post_meta($post_id, $key, $value);

$key = "your_own_farm_pics_1_alt_tag";
$value = "Alt tag content for image 2";
add_post_meta($post_id, $key, $value);

$key = "_your_own_farm_pics_1_alt_tag";
$value = "field_57ab934d407ef";
add_post_meta($post_id, $key, $value);

?>

Of course the above PHP code would go in a custom plugin and wouldn't work as standalone php code, but you should get that if you have any experience with writing WordPress plugins and if you do not, then this topic is far to advanced for you anyway. Try one of my starter tutorials for WordPress plugin developers instead.

 

Code explained:

First, you should notice the $postid variable that gets set to the post id you want to update with repeater fields.

Then you see three lines of code setting the $key variable to "your_own_farm_pics" which you will change to the name of your own repeater field name. The value of this needs to be equal to the number of repeaters you want to add. In this case, we are adding 2 images, so we set the value to 2.

Next you see the key of _your_own_farm_pics. This is the field value that is set in the database and is crucial in identifying the repeater field correctly, so be sure to get this right. Do an export of the database and search for the repeater field name to find the value for this if you have to. All you have to do it export the database as  XML and do a text search for the field name and you'll see the value right below it. The code above uses the XML example code posted above in this post.

The next important section of code, where the comment says "//next eight key/value pairs are for the two repeater field sub-field names:", is where you will have eight  sections with 3 lines of code each for the two image repeaters you add.  The important part to notice here is the numbering system used. Notice that the the first four sections of code have a zero in the keys, for example:

$key = "your_own_farm_pics_0_image";

So the value of the $key variable in the above example is made up of three parts:

  1. repeater field name: your_own_farm_pics
  2. incremented number: 0
  3. sub-field name: image

In this example, my repeater field name is "your_own_farm_pics",  the numbers start at 0 and go as high as the total number of repeater fields you add, the sub-field name in this case is "image".

Then, skip down three more lines to where you see the code:

$key = "your_own_farm_pics_0_alt_tag";

this is the second sub-field for the first repeater. so we follow the same principle as we did with the first sub-field which was image. The second sub-field name in this case is alt_tag, so we have:

  1. repeater field name: your_own_farm_pics
  2. number: 0
  3. sub-field name: alt_tag

That covers the first repeater field with it's two sub-fields. Then we want to add another repeater field with the code starting at the comment that reads: "//Start image two data:".

Notice that the number in the two $key variables has incremented to 1 in the second image's code because the numbering starts at 0 and this is the second repeater or image added.

 Summary

I hope this article sheds some light on this dimly illuminated topic dealing with Advanced Custom Fields plugin and programming your own plugin to work with it. I had a very difficult time digging up enough information to piece the above code together myself, so I truly hope this helps someone attempting to do the same thing.

 

 

Passing PHP Variables to File included with get_template_part WordPress Function

Today I had a problem where I had a WordPress page template that used get_template_part to include a section of the page like WordPress themes often do. My problem was that I did some custom coding to the theme and found it necessary to pass a variable to the file included using get_template_part.

The Problem

Let's say you have a custom page template for showing search results called special-search.php. Now let's also say that the actual search results are displayed using another template file named content-searching.php. inside of special-search.php we would normally include the content-searching.php file something like this:

get_template_part( 'template-parts/content', 'searching' );

What's wrong with that? Well, nothing unless you need to use PHP variables from special-search.php inside of content-searchnig.php. Then we have a problem. Read on for the simple solution!

Making it Possible to Pass PHP Variables to Template Parts:

The solution is actually to simply not use the get_template_part function! We can very effectively replace get_template part with a combination of the common PHP include function and the WordPress locate_template function like this:

include(locate_template('template-parts/template-name.php', $load, $require_once));

As you can see the locate_template function is called inside of the include function and locate_template takes three parameters. While, you really only need to use the first parameter in many cases, it is good to know what the other two do as well, so here are all three parameters defined:

  1. 'template-parts/template-name' - will be changed to the path and filename to your template file you used to include with get_template_part. In our example case above, this parameter would get set to 'template-parts/content-searching.php'.
  2. $load - is an optional Boolean parameter that would be set to either true or false, but which is set to false by default which is the desired setting in this case. This parameter tells the function whether or not to load the template file. We don't want the template to be loaded by locate_template since it will get loaded by the include function in this case. So if we include this parameter, we would set it to false.
  3. $require_once - is the third parameter which is also optional and set to true by default. It simply determines whether we use require_once or require to include the template file. true = requrie_once and false = require.

Example Usage:

Still using our test case scenario from above, here is how we would use the include and locate_template function together to replace get_template_part and hence be able to use variables defined in the parent file inside of the template part file. Above we said we had a template file named special-search.php that used get_template_part to include a template part file named content-searching.php. Below I will demonstrate the change that would need to be made:

Change this line:

get_template_part( 'template-parts/content', 'searching' );

into this line:

include(locate_template('template-parts/content-searching.php'));

Notice how get_template_part doesn't use the actual whole filename due to it's unique naming convention rules, but our second method however must use the whole filename. Both cases call the same file however. If you change get_template_part into the include statement shown in our example, then you will now be able to use variables defined in special-search.php within content-searching.php. Problem solved!

How to add Custom Admin Meta Boxes to a WordPress Custom Post Type

I decided to write this detailed tutorial on how to add custom field meta boxes to the WordPress admin mostly because I couldn't find a decent description of how to do it anywhere online. Hopefully this will help others having trouble trying to learn how to add admin meta boxes with custom fields for a custom post type in WordPress. It is an essential step to learning WordPress plugin development.

Let's dive in and learn some code because I believe that is the quickest and easiest way to learn this advanced WordPress method. I say it is an advanced subject because it is a little complex for beginners. If you are not sure how to start your own plugin yet in WordPress, then this topic may be too advanced for you. You should at least learn how to make a very basic WordPress plugin first, so feel free to read one of my more basic WordPress plugin tutorials first.

First of all, I'll show you how to add a single meta box with a single field in it. It is also important to know that you can have more than one field inside a single meta box. It is equally important to know that you can have more than one meta box. Each meta box can have one or more fields in them. It just depends on your individual needs. Below is the basic code for how to add a custom post type with a custom field inside of an admin meta box. I'll also include a basic plugin heading so you may follow along and create a working example to work from:

Adding a Custom Post Type to WordPress Plugin

<?php
/**
 * Plugin Name: Jafty Metabox Example Plugin
 * Plugin URI: http://jafty.com/blog/crash-course-on-wordpress-plugin-development/
 * Description: A Plugin that adds metaboxes to your WordPress blog or site.
 * Version: 1.0
 * Author: Ian L. of Jafty.com
 * Author URI: http://jafty.com
 * License: GPL2
 */
 

 //Add new Custom Post Type named videos:
add_action('init', 'create_video_posttype');
function create_video_posttype(){
    register_post_type('videos',
        array(
            'labels' => array(
            'name' => __('Videos'),
            'singular_name' => __('Video')
            ),
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'video'),
        )
    );
}//end create_video_posttype function

?>

Okay, now start a .php file and add the above code in green to the start of it. Name the file "jafty-metabox-example-plugin.php" and save it. Please NOTE: it is important to go into wp-admin/settings/permalinks and re-save those settings after activating a plugin with a custom post type or after adding a custom post type to a plugin. If you do not do this, the custom post type posts will not show up on the front end of your blog.

At this point, you should be able to upload the jafty-metabox-example-plugin.php file to your WordPress site's plugins folder and activate it. If it works, you'll see a new "Video" option in the left navigation menu of wp-admin as in the following photo:

videoCPT

Add a Metabox with a Custom Field to your CPT

Now here is the code to add to the end of the file you started above(just before the closing PHP tag) that will add a meta-box with a custom field inside of it to your plugin. It adds a field to the wp-admin edit screen for the videos CPT(custom post type):

//Add custom admin Meta Boxes:
add_action('add_meta_boxes', 'add_ians_metaboxes');
function add_ians_metaboxes(){
//add meta box for Video type and description:
add_meta_box('meta_box_html_id', 'Video Details', 'video_details_function', 'videos', 'normal', 'high');
}

//##################### Video Details Metabox: ################
function video_details_function() {
global $post;  
//Noncename needed to verify where the data originated
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce(plugin_basename(__FILE__)) . '" />';

//Get video description data if its already been entered
$video_desc = get_post_meta($post->ID, '_video_desc', true);
    
//Start video Description text field HTML:
?>
Video Description:
<input type="text" name="video_desc" value="<?php echo $video_desc; ?>" class="widefat" />
<?php
}//end video_details_function

Save the "jafty-metabox-example-plugin.php" file and update it on your site and click on the "Video" link in wp-admin and then click on "Add New" to see the add/edit screen for your new CPT. You will notice your  custom meta-box with the heading of "Video Details". You will also notice the meta-box contains a custom field named "Video Description". You can see both near the bottom of the photo below:

customField

Saving Custom Field Data

Your not quite done however. While the code above will display the metaboxes, it does not save the data as I soon discovered. To save the data, you'll need to add this code directly after your video_details callback function:

//hook into save_post to save the meta box data:
add_action ('save_post', 'save_video_desc');

function save_video_desc($post_id) {
//verify the metadata is set
     if (isset( $_POST['video_desc'])) {
     //save the metadata
     update_post_meta ($post_id, '_video_desc', strip_tags($_POST['video_desc']));
     }
}

 

 Adding Multiple Meta-Boxes and Custom Fields

Next I'll show you what out final plugin file would look like if we were to add another custom field to our meta-box and then another meta-box with yet another custom field inside of it. This way you can see how more than one meta-box is added and also how to add more than one field inside of a single meta-box. Here is the complete plugin code containing a total of two meta-boxes and three total custom fields:

<?php
/**
* Plugin Name: Jafty Metabox Example Plugin
* Plugin URI: http://jafty.com/blog/crash-course-on-wordpress-plugin-development/
* Description: A Plugin that adds metaboxes to your WordPress blog or site.
* Version: 1.0
* Author: Ian L. of Jafty.com
* Author URI: http://jafty.com
* License: GPL2
*/

//Add new Custom Post Type named videos:
add_action('init', 'create_video_posttype');
function create_video_posttype(){
register_post_type('videos',
array(
'labels' => array(
'name' => __('Videos'),
'singular_name' => __('Video')
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'video'),
)
);
}//end create_video_posttype function

//Add custom admin Meta Boxes:
add_action('add_meta_boxes', 'add_ians_metaboxes');
function add_ians_metaboxes(){
//add the first meta box for Video type and description:
add_meta_box('meta_box_html_id', 'Video Details', 'video_details_function', 'videos', 'normal', 'high');
//add a second meta box for Video Rating
add_meta_box('meta_box_html_id2', 'Video Rating', 'video_rating_function', 'videos', 'normal', 'high');
}
//################## Video Details Metabox: ####################
function video_details_function() {
global $post;

//Noncename needed to verify where the data originated
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce(plugin_basename(__FILE__)) . '" />';

//Get the video type  if its already been entered
$video_type = get_post_meta($post->ID, '_video_type', true);
// Get the video description if its already been entered
$video_desc = get_post_meta($post->ID, '_video_desc', true);

//Start type select field HTML:
?>
Video Type: <select name="video_type">
<option value="DVD"<?php if($video_type=="DVD")echo " selected";?>>DVD<option>
<option value="Blueray"<?php if($video_type=="Blueray")echo " selected";?>>Blueray<option>
</select><br />
<?php
// Start video description field HTML:
?>
Video Description:
<input type="text" name="_location" value="<?php echo $video_desc; ?>" class="widefat" />
<?php
}//end video_details_function
//##################### Video Rating Metabox: ###################
function video_rating_function() {
global $post;

//Noncename needed to verify where the data originated
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce(plugin_basename(__FILE__)) . '" />';

//Get the start_month data if its already been entered
$video_rating = get_post_meta($post->ID, '_video_rating', true);

//Start type select field HTML:
?>
Video Type: <select name="_video_rating">
<option value="R"<?php if($video_rating=="R")echo " selected";?>>R<option>
<option value="PG"<?php if($video_rating=="PG")echo " selected";?>>PG<option>
</select><br />
<?php
}//end video_rating_function
?>

//add your save data hook and function to save all fields here:

//hook into save_post to save the meta box data:
add_action ('save_post', 'save_video_data');

function save_video_data($post_id) {
//verify the metadata is set
     if (isset( $_POST['video_desc'])) {
     //save the metadata
     update_post_meta ($post_id, '_video_type', strip_tags($_POST['video_type']));

    update_post_meta ($post_id, '_video_desc', strip_tags($_POST['video_desc']));

    update_post_meta ($post_id, '_video_rating, strip_tags($_POST['video_rating']));
     }
}

That's it! Save the above code in a PHP file and name it the same name as before and allow it to overwrite the original plugin file if you were following along and it will add another meta-box and a couple more custom fields to your custom post type. Now you should have enough information to be able to make your own custom admin meta-boxes and fields for your next WordPress plugin or theme. Here is an image of the two meta-boxes from when I tested the above code myself:

metaboxes

Summary

Now you should know more than enough to make your own plugin or custom theme with its own admin meta-boxes and custom fields for any custom post types you may have. It is important to know that you can also use any other type of form element in the above examples. Feel free to experiment and use textareas, radio buttons, checkboxes etc in your own code.

 

How to Include a CSS Style Sheet for a WordPress Page Within a Plugin

For years I used to simply include CSS styles in WordPress plugins that I made for myself by doing it the same ways that you would for a pure HTML website like:

The Wrong Way:

<style>
p{
font-family: arial;
}
</style>

Or I would do it like this with an external stylesheet:

<link rel='stylesheet' href='http://jafty.com/wp-content/plugins/plugin-name/css/frontend-style.css' type='text/css' media='all' />

But I found out later when I started making professional plugins for clients that there is a more correct way to do it when using WordPress.

The Right Way to Include CSS Styles in a WordPress Plugin:

The right way to include a style sheet in a custom WordPress frontend page generated by a plugin you are making is to create the style sheet in an external CSS file and include it like this:

In your plugin's main PHP file include:

<?php

//Add frontend styles for the calendar page:
$pluginURL = plugins_url("",__FILE__);
$CSSURL = "$pluginURL/CSS/frontend-style.css";//change to your filename and path
wp_register_style( 'frontend_CSS', $CSSURL);

?>

Then,  wherever you want your style to show up, include this:

wp_enqueue_style('frontend_CSS');

I include the wp_enqueue_style function call write after wp_head normally in my custom page's header.

I normally like to have a folder inside my main plugin folder named "CSS" or "style" where I put all my CSS style sheets for the plugin. You can see I used "CSS" in the above example. You would of course alter the URL according to the folder you placed the CSS file in. The plugins_url function used with the __FILE__ definition as the second parameter will give the full URL to the plugin when it is called within the main plugin file. I normally name the main plugin file after the plugin name or sometimes i name it index.php, but regardless, the code would be the same as long as it is within the main plugin file.

In the abov example my style sheet was named frontend-style.css, yours could be named anything you like.

Using CSS Media Queries in Responsive Web Design

That's right! The post of the day is going to be on how to use CSS media queries to make a responsive web page or application. The project I'm working on requires me to create a responsive events calendar application that looks good in all sized browser windows as well as mobile devices including iPhone and Android phones and tablets. This can be done very well with CSS media queries and a basic understanding of HTML and CSS. Making today's task a little more challenging is the fact that we will be using HTML table elements. If you have any experience with HTML tables, you probably know that they can be tricky to size according to specific requirements most times. We will overcome the table cell sizing limitations in this article however.

Common Screen Sizes

One of the most important things to take into consideration when developing a fully responsive web application for both computers and mobile devices is your users screen size. What are your users likely to be using? Some will be on a PC, some on a tablet, others on an iPhone and yet others will be on an Android or other device. The ugly truth is that there are a lot of possibilities. I have found from experience that it's best to take into consideration the most commonly used screen sizes. I program for the most common and try to make it work resonably well in the uncommon sized screens as well because roughly up to 3% of your users could be using an odd sized screen that you haven't programmed for. While 3% may not sound very significant, think of it like this: If your site has 1000 visitors a day like mine does, then that means up to 30 people a day are viewing your site on a less-common screen size. 30 is 3% of 1000. Here are some of the latest statistics I could find on common screen sizes used:

First I want to show you common screen sizes of Mobile Devices since they are probably the fasting growing segment of 2016:

2016 Total iOS* Android Windows Others
February 5.15 % 1.08 % 3.49 % 0.42 % 0.16 %
January 5.38 % 1.17 % 3.69 % 0.37 % 0.15 %

The above information was collected by the website w3schools.com. The data represents the users of their website according to information collected by thier servers. It shows that only slightly greater than 5% of thier website viewers view thier site on a mobile device, but your site could have more because I think the w3schools website is one that developers reference a lot and developers do their work on a computer more often than on a mobile device. That may account for some of the low figures for mobile users. Now lets look at the most commone screen sizes according to rapidtables.com:

Common screen resolutions of rapidtables.com visitors (2/2014):

Screen resolution Display
ratio
Usage Screen size / type
1366x768 16:9 19.1% 14'' Notebook / 15.6'' Laptop / 18.5'' monitor
1920x1080 16:9 9.4% 21.5'' monitor / 23'' monitor / 1080p TV
1280x800 8:5 8.5% 14'' Notebook
320x568 9:16 6.4% 4'' iPhone 5
1440x900 8:5 5.7% 19'' monitor
1280x1024 5:4 5.5% 19'' monitor
320x480 2:3 5.2% 3.5'' iPhone
1600x900 16:9 4.6% 20'' monitor
768x1024 3:4 4.5% 9.7'' iPad
1024x768 4:3 3.9% 15'' monitor
1680x1050 8:5 2.8% 22'' monitor
360x640 9:16 2.3%
1920x1200 8:5 1.7% 24'' monitor
720x1280 9:16 1.6% 4.8'' Galaxy S
480x800 3:5 1.1%
1360x768 16:9 0.9%
1280x720 16:9 0.9% 720p TV

If you study the numbers above, they suggest that rapidtables.com visitors are much more likely to be on a smaller screen size device or mobile device than are w3scools.com users. I guess from reading the above data that their website has roughly up to 12% of their users using smaller screened devices such as iPhones, Androids and other mobile devices.

CSS Media Queries

I choose to use one simple type of CSS media queries in this challenge. I like to call it the max-width technique for sizing web pages at various sizes. This is due to the fact that the technique uses ony the max-width media query as you will see with the demonstration code below.

From studying the more common screen sizes, I've come up with a simple plan to make my calendar application look good on just about any possible screen size. Here is my rudimentary logic:

I plan to set the maximum with of the calendar to 1000 pixels and centering it on the page. By doing this I eliminate the need for any media queries for screens over 1000 px wide! As you can see from the charts above,  there are 17 screen sizes represented and 11 of them are over 1000px wide! We have already made our work a lot easier since we only have 4 other screen widths to worry about(because 3 of them have 320px wide screens). Obviously 320px is of great concern as it is one of the most common widts on mobile phones, but I'll also take into considertion the widths of 360px, 480px, 720px and 768px. However, some will be taken care of by the same media queries as you'll soon discover. Here are the basic rules we will go by when making out calendar application:

  • web page will be no wider than 1000px and centered.
  • first media query will be set for max-width of 800px meaning that if the page size is under 800px wide the styles inside of the media query definition will be altered.
  • A second media query set for a max-width of 500px will apply changes for any screen size under 500px down to the next media query.
  • A third media query set for a max-width of 400px will account for any screen between400px and the next media query.
  • A forth and final media query set for max-width of  320px will account for the common screen sizes of 320px and under which are the smallest group of mobile phones, so no other media queries after this one will be required.

I have outlined my logic above, now I can add my media queries to my CSS style sheet as follows:

/*add styles for screen sizes of 800px and up. These don't need to be inside of a media query because the table's width for the calendar will be set to 1000px and centered. Tables are generally flexible enough to be reduced from 1000 to 800px without any problems given it is styled and tested correctly.*/

@media(max-width: 800px) {
//add styles for screen sizes from 500 to 800px:
}

@media(max-width: 500px) {
//add styles for screen sizes from 400 to 500px:
}

@media(max-width: 400px) {
//add styles for screen sizes from 320 to 400px:
}

@media(max-width: 320px) {
//add styles for screen sizes 320px and under:
}

The above is a good way to start your CSS style sheet for a resposive design. You may find that you may not need to use one or more of the media query definitions. You may also find yourself adding one or two media query definitions. None-the-less, this is a good start.

Writing and Testing your CSS Code

When I make a responsive web page, I first make the basic page with basic CSS and no media queries. Then when the basic page is complete, I start testing it at different screen sizes by making my browser window smaller and larger and seeing how the page looks at every possible width and height. Then I add styles to media queries and edit them until the page looks good at every possible size. Finally I test on actual devices such as an iPhone, Android phone and a tablet while making final adjustments according to how the page looks on the actual devices.

How to Make an Image Cover the Entire Webpage Background with CSS3

CSS3 includes many fabulous new tricks. One of those is the background-size attribute which I will demonstrate below. This is what I have found to be the best way to make a background image cover the entire webpage background regardless of the screen size or browser window size. Also, this is a nice new modern cross-browser method that works in most modern browsers including:

  • Safari 3 and above
  • Firefox version 3.6 and higher
  • Internet Explorer 9 and above
  • Chrome
  • Opera 10 and above

CSS3 Style to Make Image Cover Whole Page Background

Here is the css style to add to any webpage to add a background image that covers the entire page background:

<style>

html{
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

</style>

Conclusion

This method works great for almost every site I've used it on, so give it a chance. I know CSS3 still scares some people, but using it is a pretty safe bet these days. It's been around long enough now to be considered the standard in my opinion. Some of you may have noticed that I have SEO as a category for this article. Why? That is because proper mobile development is beginning to effect search results in  Google as of April of 2015, so sites with correct mobile optimization will get ranked better! So optimize your website for mobile devices today or you may lose your Google rank!

HTML Color Chart and Color Picker

I've made several of these HTML Color Charts and Pickers of the years and I can never find one when I really need it, so I am putting a couple of them here for reference, so enjoy! These color charts will enable you to find any HTML color, hex color or RGB color you might be looking for.

HTML Hex Color Chart

You can click on any color below to get the HTML hex css color code. If you need to convert that to rgb, use the tool further down on the page to do so.

Hex RBG Color Picker

Use the slider to the right to pick a color then click in the left to get the HTML color code or enter your own color in the upper input field.

You Can Now Contribute Web Development Content

Jafty Interactive Web Development has decided to start accepting user contributed blog posts! You can now submit any post that is related to out blog theme of web development and it will be published after admin moderation. As long as it is on topic and I think it improves the quality of my blog, it will probably be published. Some topics I would like to encourage users to submit posts about include:

  • PHP
  • JavaScript
  • HTML
  • XML
  • CSS
  • Search Engine Optimization/SEO
  • Freelancing as a web developer
  • Freelance writing
  • working from home
  • Laravel
  • WordPress
  • C Languages
  • Java
  • ASP.net
  • JQUERY
  • Ruby on rails
  • MySQL Database
  • SQL
  • PHP and MySQL
  • Remote server administration
  • Linux Command Line
  • Linux and Windows Servers
  • MAC and web development
  • PC vs MAC
  • Mobile Development
  • Mobile website optimization
  • PERL
  • AJAX
  • Adwords
  • CURL
  • Graphics
  • anything else related to web development!

That's just a list to fuel your mind. Feel free to submit any related topic. I will accept anything related to web development. I'm looking forward to some great blog posts! - Ian L.

Click Here to Sign Up and Begin Writing!

 

Using XMLRPC to get a List of Posts from WordPress

Today I'm going to demonstrate how one can go about remotely fetching a list of posts for any post type including custom post types remotely using XML-RPC in WordPress. What I thought was going to be a simple task ended up taking me the majority of an entire day to work out yesterday, so I am posting my solution here for future reference and to help others solve the same problem.

So during my quest to figure out a solution for listing posts for a remote WordPress blog inside the wp-admin of another WordPress blog, I came across a couple promising functions such as wp.getPosts, blogger_getRecentPosts and similar existing XML-RPC functions that reside within wp-includes/class-IXR.php. None of those did the trick however, so below is the final solution I came up with which involves extending the XML-RPC class noted.

Extending the XML-RPC functions in WordPress

Here's what you can add to your theme's functions.php or plugin file to extend the class-IXR.php class to allow remote listing of post titles for any given registered post type:

function wp_getTits() {
// Get the 'Profiles' post type
/*$args = array(
    'post_type' => 'oils-blends',
);*/
$args = array(
'nopaging' => true,
'numberposts'    => 300,//increase if more than 300 products exist!
'post_type'        => 'oils-blends',
'post_status'   => 'publish'//only exporting published products!
);
$loop = new WP_Query($args);
$tits = "";
while($loop->have_posts()): $loop->the_post();

$titis = get_the_title();
$tits .= $titis."zxz";

endwhile;
wp_reset_query();
return $tits;
}

function wp_new_xmlrpc_methods( $methods ) {
    $methods['wp.getTits'] = 'wp_getTits';
    return $methods;   
}
add_filter( 'xmlrpc_methods', 'wp_new_xmlrpc_methods');

After you add the above code to functions.php or your plugin file, then you can use the following block of code within a plugin file of another WordPress site to remotely list the posts of a WordPress blog on another server. I added the following code inside my plugin which was used to post to a remote WordPress site. I needed to read the existing posts in order to know whether to write or update the posts that I was pushing to the second blog:

<?php
echo "<p>Starting to get posts from remote website...</p><h3>List of Titles:</h3>";

$rpcurl = "http://example.com.au/wordpress_dir/xmlrpc.php";

$request = xmlrpc_encode_request('wp.getTits','1');
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
//echo "Curl results: $results<hr />";
curl_close($ch);
//separate titles by zxz string:
$titleArray = explode("zxz",$results);
    foreach($titleArray as $curTit){
        echo "$curTit<br />";
    }//END FOREACH TITLE
echo "<p>Finished...</p>";

?>

That's all folks. Now you can remotely fetch posts from one WordPress site to another without any prior knowledge of post IDs etc. Now if you do know the post IDs, then you could use the existing XML-RPC method, wp.getPost which uses the post ID as an argument. I'll share this code with you too even though it wasn't the final solution for me, it could work for someone that happens to know the post IDs for which they need to grab remotely. The following code was tested and working as of WordPress version 4.2.3:

Listing Posts Remotely using wp.getPost

As you will see, it is a lot easier to get post data when you know the post ID. Here is all you have to add to your WordPress plugin file to remotely grab a post using wp.getPost when you know the post's ID:

<?php
echo "<p>Starting to get post data from remote site...</p>";

$rpcurl = "http://example.com.au/wordpress_dir/xmlrpc.php";
$username = 'admin';
$password = 'password';
$post_id = 2820;
include('../wp-includes/class-IXR.php');  
        $client = new IXR_Client($rpcurl);
     
        $USER = $username;
        $PASS = $password;
               
        if (!$client->query('metaWeblog.getPost',$post_id, $USER,$PASS))
        {  
            echo('Error occurred during getting post.' . $client->getErrorCode().":".$client->getErrorMessage());  
        }
        $post = $client->getResponse();
       
        var_dump($post);
echo "<hr /><p>Finished....</p>";
?>

Of course you have to edit the URL, username and password above, but after that it will work fine.

Summary

So I've given you two ways to get post data from WordPress sites remotely. If you know the post IDs, then use the last method which is simpler, otherwise you have to extend the class explained above using the first two code snippets on this page. Good luck!

Fixing Encoding Problems When Creating WordPress Posts With PHP

I'm documenting this simple fix because it took me over an hour to figure out. I was writing a WordPress plugin that would publish custom post types from one blog to many others. In doing so, I used PHP to write code that would read posts from the master blog and write them to another blog, or several blogs actually. The problem was that some characters such has hyphens and the letter y would end up encoded incorrectly in the blog that the post was copied to. Here's two images that show what happened. The first is an image of the WYSIWYG editor in WordPress when viewing the post in the edit screen using the text tab. The second image is when viewing the post in the HTML tab of the WYSIWYG editor:

txt htm...so as you can see in the areas I've circled above, there is definitely something wrong with the character encoding happening somewhere.

Fixing Character Problems in WordPress and PHP

The solution was to use the following line of code on the post text before writing it to the WordPress database:

$txt = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $txt);

By using the PHP iconv function to convert the txt variable to a new encoding, I was able to stop the encoding problem and all was great! I'm not going to explain this in detail because frankly the finer details of PHP and HTML encoding elude me to this day after coding for over 15 years. I understand we need different encoding for different languages, but why can't we have more of a standard? It would make life so much easier!

Summary

I hope this helps someone as it did me. Good luck with your own encoding problem. I find it is often necessary to play with several PHP encoding functions to solve various problems, so if this doesn't do the trick, try htmlentities or utf8_encode and similar PHP functions to modify your text.

CodeLobster All-in-One Coding Software

CodeLobster PHP Edition Software Review

Written by Ian Lincicome of Jafty Interactive Web Development - Jafty.com

For the past couple of weeks, I have been evaluating CodeLobster's latest release of "CodeLobster PHP Edition" which I'll refer to as simply "CodeLobster" from here on out in this review. The current edition at the time of writing this review was CodeLobster PHP Edition Professional Version 5.4. I am reviewing CodeLobster because I am looking for a tool I can use for my web development business, Jafty Interactive Web Development. Also I was given a break on purchasing the pro version of CodeLobster in exchange for writing a product review on my site, Jafty.com. Please note that I am under no obligation to write a positive review. I will be as brutally honest as ever, I assure you. This review will include both the pros and cons of using CodeLobster rather than a one-sided review like many company's probably hire writers to write. In fact, if that was my intention, I wouldn't have mentioned that the someone had asked me to write this review. My ulterior motive for writing the review is to find the perfect program to do my work for my business. I am also evaluating other products as well because I want to work with the best.

I'm looking for an application that will allow me to seamlessly edit several types of code on several different servers without having to use a separate code editor, FTP program, web browser and Language reference material. To this date, I have been using three separate applications to accomplish my day-to-day work. I used FileZilla to copy files from a client's web server to my desktop. I used Notepad++ to edit the code files. Finally, before using FileZilla again to upload the files back to the client's server, I viewed the file in Firefox to see how it looks in a browser. That is if it is not a server-side language like PHP which I use the most. If I had to edit a PHP file, I had yet another couple of steps to perform because I'd have to upload the file to the server to view it and then repeat the whole entire process again if I had more changes to make to get it perfect. So I used FileZilla, Notepad++ and Firefox mostly up until now. I figure I could probably almost double my productivity with one good tool that does it all.

Technologies CodeLobster Supports

CodeLobster supports a wide range of technologies including:

  • PHP
  • HTML
  • JavaScript
  • CSS
  • SQL
  • MySQL
  • Version control systems such as SVN, Git etc.
  • CakePHP
  • CodeIgniter
  • WordPress
  • Drupal
  • Joomla
  • Facebook
  • jQuery
  • Smarty
  • Symfony
  • Yii

CodeLobster also has a very wide assortment of features including all the standard components you would expect in a code editor and many extras. I found a helpful built-in Help feature that also links to online help if you can't find what you need in the built-in documentation. The online documentation is surprisingly complete for a newer product.

Installing CodeLobster

The installation went smoothly and was very easy and comprehensive. Simply download and click the set up file and the installer will guide you through the simple set up process. Here is the Download Link: http://www.codelobster.com/download.html

When I first installed CodeLobster, it allowed me to select what languages/technologies I wanted to install. I only deselected two that I knew for sure I would most likely never use. I figured if there was even a small chance that I might use one of the items listed, then I should leave it checked. That way I will be prepared in case I need that particular technology in the future.

Pros and Cons

Once I began using CodeLobster I noticed both good and bad points regarding the program. I loved how versatile the program was right out of the box. I did not like the way the word wrap feature worked(View/Word Wrap). It breaks up words rather than splitting lines by the nearest space. I'd prefer it to not break up words at all or at least do so in a more logical manner(by syllables with hyphens for example). From what I understand from reading the forums and talking with my contact, CodeLobster plans to add an option between soft and hard word-wrap. Hard wrap is how it is now and soft wrap would be a word-wrap technique that doesn't break up words. I do hope they add it soon because it was one of the of the first things I noticed.

One of the first features I noticed and liked was the completely configurable hot-keys. You can configure any hot-key by going to Tools/Preferences/IDE/Hot keys. Another nice feature is the Find and Replace feature that is very much like that of Notepad++ including regular expression search and the ability to search and replace text in files, folders and sub-folders. This can be a huge time-saver for coders.

One of the first things I noticed and did not like was the lack of a decent spell checker. I know notepad++ has the option as a plugin, but not as a built-in feature. Either way would be great, but I think it should be a standard built-in feature. I realize that auto-complete helps with this, but not if you are writing a plain text file such as I am doing right now while writing this review. I talked to my contact at CodeLobster Software about this and he assured me that they plan to add a robust spell-checking feature in the near future. He mentioned that they plan on making several additions to the software and will be releasing future editions with new features and improvements ASAP. So, while CodeLobster may not have everything I would like it to have at the moment, I was assured that they are heading in the right direction with future expansion plans.

Another nice feature I also noticed right away was CodeLobster's tool bars. The tool bars are completely configurable and have a nice drag and drop feature to move tool bar items around as you please. The same can be said for the man different windows that can be added or removed from the work area.

CodeLobster is a code editor first & foremost and it does a wonderful job at editing PHP code which is my code of choice. If you are looking for a word processor, CodeLobster probably won't fit the bill, but it is a very robust code editor that can handle all of the languages I use for web development and several others.

CodeLobster's plugin ability is great to have in a code editing program. The pro version of CodeLobster comes with many plugins that the free version does not include from what I understand, so I think the pro version is definitely worth the cost for those of you who work with frameworks such as WordPress, Joomla, CakePHP, CodeIgniter, etc. I currently own the Pro version and I am happy with its performance so far and will be much happier once some of the additions are made in the near future.

Even the free version would be great for coders who use many different coding languages regularly but don't need the extra plugin abilities that require the pro version. As a full-time web developer, I mostly use PHP, HTML, CSS, JavaScript, WordPress and MySQL. I also occasionally use Joomla, XML, Perl, Python, Drupal, Smarty, Laravel, CakePHP and others, so I require the Pro version of CodeLobster myself. If you only use the most common languages such as PHP, HTML, CSS and JavaScript, you can probably do fine with the free version. Some of the things I require the Pro version for include WordPress support, Smarty, Laravel and CakePHP. Honestly there are to many features to list here. You should visit their web page at http://www.codelobster.com/details_phped.html to figure out which version is best for you. They also have a Lite version which you can read about on their site since I won't be covering CodeLobster Lite here.

As I continue to evaluate the software I am finding there are more and more features that I like. As a web developer, I need a tool that allows me to quickly edit code, test it and upload it to the client's server. So far, CodeLobster seems to be meeting my three main requirements quite well in most cases.

FTP Feature

CodeLobster's FTP ability is a very powerful feature. The FTP feature allows you to set up as many FTP connections as you need. I was able to copy all of my client's FTP connections from FileZilla into CodeLobster. Now I am able to click on a connection, edit a server file, preview it and upload it back to the server seamlessly from within a single application! This is huge for me because I used to use at least three different applications to do the same thing without CodeLobster. I can see that my work will get done a lot faster by using CodeLobster. In fact, I am already getting work done faster after only two days of using it.

The FTP feature is very functional, but for a guy like me who hates to read instructions, it took a little bit of fooling around using trial and error methods to get it set up for the first time with all of my client's 20+ FTP connections and configuring basic settings. Everything I needed to accomplish my FTP tasks is in CodeLobster, but the FTP system does need some improvements. For example it gave me trouble when trying to connect to a SFTP connection. It worked great with all non-secure FTP connections however. As luck would have it, out of over 20 current clients I work with, only one uses SFTP rather than FTP, so I am unable to test it on other secure SFTP servers to see if the problem is just with this one server or not. Unfortunately this is one of my regular clients so it is going to be a problem for me. It did connect using SFTP, but had issues when trying to edit files on the server which I was able to do fine with regular FTP connections. I did bring this issue to the attention of my CodeLobster contact however and he assures me it will be looked into ASAP.

Regarding the GUI set-up for FTP, in my personal opinion, the way the windows are organized in the work area could have been done a little better. For example, when I use FTP, I have to go to Tools/FTP to open the explorer window that lists FTP connections. That alone will allow you to open your FTP connection but won't allow you to see what's going on. If there was an error and the only window you had open in your work area was the explorer window, you wouldn't see that error. This is where I think it could have been done better. I would have programmed it so that when you open the FTP window, the output window opens along with it, right above it, similar to how FileZilla allows you to view console output. Of course this is just my opinion, it may not bother others and actually I am starting to get used to it so it doesn't bother me as much as time passes.

Search Features

The "Find in Files"(Search/Find in Files...) feature is great for finding text in open files. It could be improved to allow file search on the local directory tree files as well, but it is sufficient the way it is. Also I love the regular expression search as I mentioned earlier.

Also, I often use the incremental search feature when I edit code. While I am glad it has this feature, a small nuisance for me is that the incremental search box is not persistent across different views. I think it would be nice if the incremental search box would stay at the bottom of all view tabs once it is opened. I don't think it should close unless you manually close it. Again, this is just my preference, not a bug.

Nice-to-Have Features

One more thing I liked while test driving CodeLobster is that when editing .html and .css files I could hover over class names in the HTML or CSS code and it would show me the associated style declaration. Also when hovering over items in a .css file, it shows me information regarding the browser compatibility of the CSS code.

The HTML preview feature works very well. It is a built-in browser that shows the results of your code live without having to open a separate browser window. All you do is click on the "preview" tab. I did notice that sometimes you have to hit the refresh button to see your changes, but that is to be expected.

I also enjoyed the code formatting features very much. I tested them on an HTML file that I copied from an online web page. At first the HTML code was ran all together with no line breaks or indents. I simply went to the tool bar and clicked "Tools/Code Format/Format" and it formatted it perfectly. I am sure it will work with other supported languages equally well.

When you double-click on a variable name in the PHP editor, it highlights the variable and the dollar sign, so you can copy the whole thing and paste or search for it easily. Notepad++ wouldn't include the dollar sign and it was a bother to me.

CodeLobster has what they call a "Map" feature(View/Windows/Map) that I've never seen before. It is basically a small window with a tiny view of the document you're working on. It allows you to click anywhere in the Map to quickly jump to a section of the file that you need to work on. It is a great feature for working with large files.

Conclusion

I have concluded that CodeLobster will indeed fill a need in my current web development process. It is not yet developed enough to be the only tool I use simply because of that one SFTP connection it will not work correctly with. However I found that I can combine it with another tool, CyberDuck, as a work-around until the developers of CodeLobster work out the final kinks in the software and add some more nice-to-have type features such as spell-check and . In the end it still gets a thumbs up for all the wonderful features it has and for its robustness in general. Eventually I believe it will make the perfect all-in-one coding tool for my company. The other contender for my new all-in-one coding tool was CyberDuck and I can honestly say that CodeLobster has much more potential. CyberDuck is also in its early stages of development and it needs several improvements to be truly useful. CyberDuck fails in comparison to CodeLobster when it comes to Features. CodeLobster is truly made to be an all-in-one coding solution while CyberDuck is missing many of the necessary features to be a real competitor.

If you are interested in how I combined CodeLobster with CyberDuck to make up for CodeLobster's short-coming when connecting by SFTP, I'll quickly go over how to do it. Create a bookmark(that's what CyberDuck calls their FTP/SFTP connections) in CyberDuck to the SFTP server. CyberDuck allows you to set it up so you can use your own code editor with it in a way that allows you to click on a file from a remote server and open it in that editor. Then when you save it in that editor(CodeLobster), it saves it to the server. That way I still have a seamless process even though I have to combine two tools to get what I truly want.