My Toolset Tips

Toolset is great to build almost everything within WordPress and when things get complicated they also have a great Technical Support.

On Toolset Professional Support forum I use to look for all the tricky solutions to complete the most complex tasks. There are a lot of simple PHP hooks that any developer can easily add to make more magic with Toolset.

Toolset is not only good because it allows you to build your website without coding, it is powerful because of it’s API and the possibility to extend and customize almost everything.

Here I will list some of the most useful that I use to add to my functions.php or in a Toolset Custom code snippet (Toolset>Settings>Custom code). Most of them are shortcodes, don’t forget to register them on Toolset>Settings>Front-end Content>Third-party shortcode arguments.

Sometimes the user have a smoother experience if it is possible to login automatically after registration. For example, I’ve used this functionality on a directory website where registered users can publish their own business.

On the add business page, if the user is logged in, I display my “add new business” Toolset Form, if the user is not logged in, I display the login form and a Toolset User Form to register new users.

Instead of reload the login form after register, I can reload the page, then auto-login the user and display the my “add new business” Toolset Form.

I can do this with this function called by a cred_save_data action:

/**
* Auto-login new Toolset User Form
*/
add_action( 'cred_save_data', 'tssupp_cred_autologin', 10, 2 );

function tssupp_cred_autologin( $post_id, $form_data ){

  if ( $form_data['id'] == 55 ) { // Edit as required

    if ( !empty( $_POST['user_login'] ) && !empty( $_POST['user_pass'] ) ) {

      // get the user credentials from the $_POST object
      $user = array(
        'user_login' => $_POST['user_login'],
        'user_password' => $_POST['user_pass'],
        'remember' => true
      );
      $login = wp_signon( $user, false );

      if ( is_wp_error($login) ) {
        error_log( $login->get_error_message() );
      }

    }
  }
}


wp_signon() reference: https://codex.wordpress.org/Function_Reference/wp_signon
is_wp_error() reference: https://codex.wordpress.org/Function_Reference/is_wp_error

Remember to change “$form_data[‘id’] == 55” with your Toolset User Form ID.

You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/automatically-log-in-user-after-created/

With Types it’s possible to add User Custom Fields, this is very useful to extend WP User’s attributes, but in certain cases it is better to work with a standard Custom Post Type (CPT) to create a real “User Profile”. This is because a standard CPT is more flexible, it works better with Views and you can connect it with other CPTs by Toolset relationships.

For example, it’s possible to use the authorship of posts to group them because each post is connected to a user author (ex: articles written by a certain WP User can be filtered by author), but if it is needed to create a many-to-many relationship between posts and authors (ex: an author can write many articles, but an article can be also written by many authors) it is necessary to create a User Profile CPT.

The architecture is simple, each WP User is author of a User Profile CPT post. The User Profile post can be connected to any post of any other CPT.

User registration flow would be: the user register a new WP User by a Toolset User Form, then the logged in user has to create the User Profile post by a Toolset Form.

It is possible to make this process smoother by creating the User Profile post automatically on user registration.

I can do this with this function called by a cred_save_data action:

add_action('cred_save_data', 'my_save_data',10,2);
function my_save_data($post_id, $form_data) {

  // User - Register - FORM
  if ($form_data['id']==55) {

    $user_info = get_userdata($post_id);

    // User profile CPT add
    $user_profile_id = wp_insert_post(array (
      'post_type' => 'user-profile',
      'post_title' => $user_info->display_name,
      'post_name' => $user_info->user_login,
      'post_author' => $user_info->ID,
      'post_content' => '',
      'post_status' => 'publish',
      'comment_status' => 'closed',
      'ping_status' => 'closed',
    ));
  }
}


get_userdata() reference: https://developer.wordpress.org/reference/functions/get_userdata/
wp_insert_post() reference: https://developer.wordpress.org/reference/functions/wp_insert_post/

The function retrieves all the user’s data by get_userdata($post_id) (where $post_id is the WP User ID created by the Toolset User Form), then use the information to create a new post by wp_insert_post() functions. The function assigns the post to user-profile CPT and it uses: the display name as post Title, the login name as Slug and the user ID as Author.

Remember to change “$form_data[‘id’] == 55” with your Toolset User Form ID and “‘post_type’ => ‘user-profile'” with the slug of your User Profile CPT.

It is possible to combine this script with snippet.

When users can publish content on a website, it could be useful to limit the extension of the text they can publish. For example, it is possible to offer the option to write a short description and a larger description.

It is possible to do it on a Toolset Form by adding some jQuery. This script limits the number of characters and adds a counter to display the number of remaining characters. This is the result:

textarea-limit

This is the form HTML:

  <label>Description</label>
  [cred_field field='description' force_type='field' class='form-control' output='bootstrap' class='description']
  <span id="chars">250</span> characters remaining


This is the jQuery snippet:

jQuery( document ).ready(function() {
  jQuery('textarea.description').attr('maxlength','250');
  var maxLength = 250;
  jQuery('textarea.description').keyup(function() {
    var length = jQuery(this).val().length;
    var length = maxLength-length;
    jQuery('#chars').text(length);
  });
});


It is possible to change ‘textarea.description’ to use it on any text field.

You can find this solution on this blog:

http://geoffmuskett.com/really-simple-jquery-character-countdown-in-textarea/

Toolset Relationships is another powerful feature of Toolset. When it creates a many-to-many relationship, it creates an intermediary CPT. By default the title and slug of the intermediary post are created by “relationship_title: parent_ID – child_ID” and “relationship_slug-parent_ID-child_ID”. For example, if we have the relationship “Writers Books”, the intermediary title would be “Writers Books: 205 – 167” and the slug “writers-books-205-167”.

If for some reason you need to display intermediary posts on front-end, it is possibe to customize intermediary post title and slug by wp_insert_post() hook.

The snippet will build the new title and slug with this structure: “parent_title child_title” and “parent_slug-child_slug” (ex: “Writer1 Book1” and “writer1-book1”).

// Custom intermediary post slug

add_action( 'wp_insert_post', 'hook_for_intermediary_post', 10, 3 );
function hook_for_intermediary_post( $post_id, $post, $update ) {

  // execute only if a new post is being inserted
  if ($update == false) {

    // post-relationship slug
    $relationship_slug = "parent-child";

    // If this is a revision or not the post that we need to target, return.
    if ( (wp_is_post_revision( $post_id )) || ($post->post_type != $relationship_slug) )
      return;

    // default slug of the created post
    $post_existing_slug = $post->post_name;

    // extracting parent and child post IDs from the slug
    $post_existing_slug_arr = explode('-', $post_existing_slug);

    $parent_id = $post_existing_slug_arr[2];
    $child_id = $post_existing_slug_arr[3];

    // getting title and slug of the parent post
    $parent_title = get_the_title($parent_id);
    $parent_slug = get_post_field( 'post_name', $parent_id );

    // getting title and slug of the child post
    $child_title = get_the_title($child_id);
    $child_slug = get_post_field( 'post_name', $child_id );

    $update_post = array(
      'ID'            => $post_id,
      'post_title'    => $parent_title." ".$child_title,
      'post_name'     => $parent_slug."-".$child_slug,
    );

    // Update the post into the database
    wp_update_post( $update_post );

  }
}


wp_insert_post hook reference: https://developer.wordpress.org/reference/hooks/wp_insert_post/
wp_update_post() reference: https://developer.wordpress.org/reference/functions/wp_update_post/

It will works on relationships creation on back-end and on frontend with Toolset Forms.

This is a classic for me!

Many times I need to makes some mathematics with custom fields, for example, if I need to sum two values stored in two custom fields, or I want to calculate a percentage based on two values or any mathematics operation.

I can add this shortcode:

// Calculate shortcode

add_shortcode('wpv-calculate', 'calculate_shortcode');
function calculate_shortcode($atts) {
return wpv_condition($atts);
}



Then I can use this shortcode anywhere:

[wpv-calculate evaluate="..."]



The attribute “evaluate” can get any  mathematics operation and use custom fields as variables. For example:

[wpv-calculate evaluate="([custom-field-1] + 5) * [custom-field-2]"] 
[wpv-calculate evaluate=" [custom-field-1] / [custom-field-2] * 100 "] %



It is also possible to round the result adding PHP round() to the function return:

// Calculate and round shortcode

add_shortcode('wpv-calculate', 'calculate_shortcode');
function calculate_shortcode($atts) {
$atts = wpv_condition($atts);
return round($atts);
}


round() reference: https://www.php.net/manual/es/function.round.php

You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/calculating-with-field-values/

Sometimes it is useful to include WordPress Sidebar in a Content Template or a View. It is possible to build a shortcode to display it:

// Display WP Sidebar shortcode 
add_shortcode('wpv-dynamic-sidebar', 'my_sidebar_shortcode');
function my_sidebar_shortcode($atts) {
  ob_start();
  $a = shortcode_atts( array(
    'sidebar' => 'sidebar-1',
  ), $atts );
  dynamic_sidebar($a['sidebar']);
  return ob_get_clean();
}


dynamic_sidebar() reference: https://developer.wordpress.org/reference/functions/dynamic_sidebar/

Then I can use this shortcode anywhere:

[wpv-dynamic-sidebar]



By default this displays the default sidebar or ‘sidebar-1’. It is also possible to pass another sidebar name by the attribute “sidebar”. For example:

[wpv-dynamic-sidebar sidebar="footer-1"]



You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/insert-sdiebar-in-views-template/

Many times it is important to store numbers in a plain format like “25970”, but maybe I need to display it like “25.970,00€” or  “$25,970.00”. This shortcode formats a number with grouped thousands.

I can add this shortcode:

// Money format shortcode (€ format)
add_shortcode('wpv-format-money', 'format_money');
function format_money( $atts ) {
extract( shortcode_atts( array(
'price' => '0'), $atts) );
return $price = number_format($price, 2, ',', '.');
}


// Money format shortcode ($ format)
add_shortcode('wpv-format-money', 'format_money');
function format_money( $atts ) {
extract( shortcode_atts( array(
'price' => '0'), $atts) );
return $price = number_format($price, 2, '.', ',');
}



Then I can use this shortcode anywhere:

[wpv-format-money price="..."]



The attribute “price” can get any custom field. For example:

[wpv-format-money price="[custom-field-1]"]



You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/need-to-display-numeric-custom-field-in-european-decimal-format/

The WordPress human_time_diff() function returns the difference between two timestamps in a human readable format such as “1 hour”, “5 mins”, “2 days”. It is possible to use it to build a shortcode to display how long time a post was posted:

// human_time_diff shortcode
add_shortcode( 'wpv-human-diff', 'human_diff_func' );
function human_diff_func( $atts ) {
return human_time_diff( get_the_time('U'), current_time('timestamp') );
}



Then I can use this shortcode anywhere:

[wpv-human-diff]


human_time_diff() reference: https://developer.wordpress.org/reference/functions/human_time_diff/

You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/date-display-problem/

Sometimes it is useful to include a WordPress Menu in a Content Template or a View. It is possible to build a shortcode to display it:

// Display WP Menu shortcode 

add_shortcode('wpv-menu', 'print_menu_shortcode');
function print_menu_shortcode($atts, $content = null) {
  extract(shortcode_atts(array( 'name' => null, 'class' => null ), $atts));
  return wp_nav_menu( array( 'menu' => $name, 'menu_class' => $class, 'echo' => false ) );
}


wp_nav_menu() reference: https://developer.wordpress.org/reference/functions/wp_nav_menu/

Then I can use this shortcode anywhere:

[wpv-menu name="main-menu"]


It is also possible to replace “main-menu” with any menu’s slug.

You can find this solution on this Toolset forum thread:

http://stephanieleary.com/2010/07/call-a-navigation-menu-using-a-shortcode/

Sometimes it is useful to add WordPress post Comments in a Content Template or a View. It is possible to build a shortcode to display it:

// Display post Comments shortcode
add_shortcode('wpv-post-comments', 'my_post_comments');
function my_post_comments() {
       ob_start();
       comments_template();
       $data = ob_get_clean();
       return $data;
}


comments_template() reference: https://developer.wordpress.org/reference/functions/comments_template/

Then I can use this shortcode anywhere:

[wpv-post-comments]



You can find this solution on this Toolset forum thread:

https://toolset.com/forums/topic/show-comments-and-comments-form-within-a-view/

There are some standard Toolset shortcodes that I use very often. All of them are included on the Views shortcodes list of Toolset Documentation.

Some of these shortcodes are not available on Views GUI, so if you need them you have to look for them on Documentation. Some other are on the GUI, but sometimes it is not so fast to include them by the Views GUI. Usually the GUI print them with double quotes inside (ex: [wpv-bloginfo show=”wpurl”], but sometimes I need them with single quotes, for example, to include them in a link “href” attribute or in a Toolset wpv-conditional shortcode.

So, this is my list:

Website URL to include in a <a href=””> or <img src=””> tags:

[wpv-bloginfo show='wpurl']


<a href="[wpv-bloginfo show='wpurl']">My Site</a>



Access the value of any View shortcode attribute:

[wpv-attribute name='view-attribute']



Access the value of any URL parameter:

[wpv-search-term parm='url-param']



Get number of posts on the current paginated page and get the total number of posts in the loop:

Showing [wpv-items-count] posts of [wpv-found-count] posts found.



Sometimes I build a View to get a simple array of values, for example, a list of post IDs separated by commas. Usually I need it this to pass the result in a another view attribute, so I need a clean and no spacing output, like “34,56,78,90”. I use this code in the view loop editor:

[wpv-layout-start][wpv-items-found]<!-- wpv-loop-start -->[wpv-item index=1][wpv-post-id][wpv-item index=other],[wpv-post-id]<!-- wpv-loop-end -->[/wpv-items-found][wpv-no-items-found][/wpv-no-items-found][wpv-layout-end]


Don’t forget to check the option “Disable the wrapping DIV around the View”, so you get a completely clean output:

Disable the wrapping DIV around the View

This is a list of shortcodes to get users data that I often need with single quotes to use inside wpv-conditional:

[wpv-post-author format='meta' meta='ID']


[wpv-current-user info='role']


[wpv-current-user info='id']


[wpv-current-user info='logged_in']



For example to display something only to logged in users:

[wpv-conditional if="( '[wpv-current-user info='logged_in']' eq 'true' )"][/wpv-conditional]



Get the complete list of Views shortcode here:

https://toolset.com/documentation/user-guides/views/views-shortcodes/