shortcode – wpv-array-contain-string

Toolset Conditionals can’t evaluate if a string is included in a list of values. For example, if I want to check if a certain post ID is included in a list of IDs, this will not work within the default conditional shortcode:

[wpv-conditional if="( '624' eq '5,8,7,12' )"]It is included!![/wpv-conditional]

To do this it is necessary to setup a custom shortcode:

// Array contain string shortcode

add_shortcode( 'wpv-array-contain-string', 'array_contain_string');
function array_contain_string($atts) {
  extract( shortcode_atts( array(
    'string' => '',
    'array' => ''
  ), $atts) );

  $result = "false";
  $array = explode(',', $array);  

  if (in_array($string, $array)){
    $result = "true";
  return $result ;

Then I can use this shortcode anywhere:

[wpv-array-contain-string string="..." array="..."]

The attribute “string” can get any custom field and “array” can be populated by a static list of elements separated by commas or a list generated by a View. For example:

[wpv-array-contain-string string="[wpv-post-id]" array="7,11,16"]
[wpv-array-contain-string string="[wpv-post-id]" array="[wpv-view name="featured-posts-ids"]"]

The output of the shortcode is “true” or “false”. We can use it in a conditional to check if the string is included (true) or not (false) in the list.
It is possible to use it directly inside the Toolset Conditional if the “array” value is a static list, but it will not work if it is a View. In this case, we need to create a Content Template to contain the custom shortcode and use it in the conditional like on these examples:

// "Array" is a static list

[wpv-conditional if="( '[wpv-array-contain-string string='[wpv-post-id]' array='7,11,16']' eq 'true' )"]
  YES, it is included!!

// "Array" is generated by a View - THIS WON'T WORK!!

[wpv-conditional if="( '[wpv-array-contain-string string='[wpv-post-id]' array='[wpv-view name="post-ids"]']' eq 'false' )"]
  NO, it isn't included!!

// "Array" is generated by a View and the shortcode [wpv-array-contain-string string='[wpv-post-id]' array='[wpv-view name="post-ids"]'] has been inserted in a content template 

[wpv-conditional if="( '[wpv-post-body view_template='array-contain-string']' eq 'false' )"]
  NO, it isn't included!!

This tip is based on this Toolset forum thread:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>