Shortcode to check if a param is in a list of options

Est. Reading: 2 minutes
By: Lisa Thrower
Created: 05/23/2023
Category:
Difficulty: Intermediate

Shortcode to check if a param is in a list of options

This is not very elegant and could easily be expanded, but while it was fresh in my head, I thought I would share it in case it helps anyone.

The shortcode asks for two attributes: name and values

  • Name = the name of the parameter that will be passed to the shortcode
  • Values = a comma separated list (you could use frm-condition if you only had one), which will be checked to see if the value of the parameter is included.

If the param value is contained in the list, it will hide any content you've put in between the opening and closing shortcodes.

E.g.

Your View: [check_param_list name="project" values="Project A, Project B, Project C"] Here's the content I want to show if the project is NOT listed[/check_param_list]

Scenario 1 - Your project param = Project A: Nothing will show

Scenario 2 - Your project param = Project D: "Here's the content I want to show if the project is NOT listed" will be displayed

This was my quick and dirty way of handling a situation where I have a standard view for most projects using a central form, but there are a handful of projects that have custom views. In this situation, I don't want to have lots of separate pages for each one. By using this approach, I can have a single page with this shortcode (which has the standard view as its content), followed by two (for now) frm-condition shortcodes, one for each of the projects that have custom views. If I need to add an additional custom view I can add the new project to the list of values and include an additional frm-condition shortcode to display the custom view.*

While being a bit clunky, it has the advantage of being able to be edited/added to by colleagues who are unable to edit shortcodes directly.

Here's the PHP for the shortcode, which can be added to theme functions or via the code snippets plugin.

add_shortcode('check_param_list', 'check_param_value_against_multiple_values');
function check_param_value_against_multiple_values( $atts, $content="" ) {
if ( ! isset( $atts['name'] ) || ! isset( $atts['values'] ) ) {
return $content;
}
$get_param_name = isset( $_GET[ $atts['name'] ] ) ? $_GET[ $atts['name'] ] : '';
$get_param_name = utf8_decode( urldecode( $get_param_name ) );
$values_array = explode(",",$atts['values']);
if (in_array($get_param_name, $values_array)) {
$content = "";
}
return do_shortcode( $content );
}

 

Leave a Reply

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crosschevron-leftchevron-rightarrow-right