Create your own visual composer widget

Today we are going to explain how you can create your own widget for the popular plugin “Visual Composer”. To start with you will need a copy of Visual Composer and a WordPress install somewhere to apply the code.

  1. Open your favourite text editor and create a new file called shortcodes.php and save it to a folder where you can upload to your website for later.
  2. Begin with having an idea of what you want to do with the widget, is it a carousel or something more complex like a google map with location pins. Whatever you decide you should make sure you have your widget well planned in advance.
  3. Ok lets have a look at coding a Visual Composer widget:

First we will look at creating our shortcode:

add_shortcode( 'm_date', 'postDate' );
function postDate( $atts ) {
    extract( shortcode_atts( array(
        'css_field' => 'css_field'
    ), $atts ));
if(isset($atts['css_field'])): $css = $atts['css_field']; endif;
     $output = "";
     return $output;

Above we create a shortcode called “m_date” and a callback function of postDate. Within the postDate function we extract some specific attributes to use such as giving your date field a css class name. We then move on to check for any css class entry in the widget before we output and return the date.

Next we will need to be able to add this as a widget to our Visual Composer interface.

add_action( 'vc_before_init', 'add_date' );
function add_date() {
   vc_map( array(
      "name" => __( "Post Date", "2b" ),
      "base" => "m_date",
      "class" => "",
      "icon" => "vc_general vc_element-icon vc_icon-vc-gitem-post-date",
      "category" => __( "Content", "2b"),
      "description" => __( "Show date of post" ), 
      "params" => array( 
               "type" => "textfield", 
               "holder" => "div", 
               "class" => "", 
               "param_name" => "css_field", 
               "value" => array(), 
               "heading" => __( "CSS", "2b" ), 
               "description" => __( "Add specific CSS class to date field", "2b" ) ) ), 
          ) ); 

So, we use an add_action hook to place this code before Visual Composer loads with “vc_before_init” and use a callback function called “add_date”. We then need to map these fields to the correct place in Visual Composer using “vc_map”. We can see from our array items that the “base” refers to the shortcode name we created earlier and we give it a name such as Post Date. The other fields are self explanatory but the params field needs to reference the param_name to the shortcode attribute css_field.

Once you have saved your file you can copy and paste to your wordpress theme functions.php file at the very end, you can then save the file and upload to your theme.

Next open your admin page with Visual Composer and try to add an item, you should see your new widget placed in the Content section of the pop up.