12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Feb 18, 2022

Conditional Code Based on Meta Box Select Field Value

Sridhar Katakam

In the WPDevDesign Facebook group, a user asks:

I've created a repeater element with information for events, which the user fills in via a Metabox CPT.
Now I want to give the user via a select menu the option to display a certain URL, depending on the option the user chooses.
Like, the user selects on the CPT dashboard Page 1 and on the front end a link to Page 1 is showing up. (see example images)

This members-only tutorial provides the steps to conditionally output dynamic HTML for a link based on the value selected for the post from the select dropdown.

Step 1

Install and activate Meta Box and Meta Box AIO plugins.

Go to Meta Box > Custom Fields and create a new group named say, "Post Fields" (if your field group is for post post type) or "Event Fields" (if your field group is for event post type) etc.

Add a Select type of field and configure it like this:

Step 2

Edit your posts and populate the custom field for each.

Step 3

Let's ensure that there's no "Undefined Function Error" when Meta Box is deactivated by accident as we will be using its rwmb_meta() function in the next step.

Install and activate Code Snippets plugin.

Go to Snippets > Add New.

Title: Prevent "Undefined Function Error" when Meta Box is deactivated

Code:

if ( ! function_exists( 'rwmb_meta' ) ) {
    function rwmb_meta( $key, $args = '', $post_id = null ) {
        return false;
    }
}

Set the snippet to run everywhere. Save changes and activate.

Step 4

In the template that applies to all the items of your post type, add this code:

This is a premium members-only content.

To view the rest of the content, please sign up for membership ($47/month or $599 one-time).

Already a member? Log in below or here.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right