12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on May 1, 2019

Displaying a custom field only if it has a value in Oxygen

Sridhar Katakam

Note: This tutorial is no longer needed. It is recommended to instead use the built-in Dynamic Data condition of Oxygen.


In Oxygen‘s Facebook group a user asked:

Q2) The Author CPT has custom fields for social URLs. I would like to use the ACF as the link on the respective social Icons… ONLY if the field has data. Can I wrap a peice of oxy content in php that checks if the field has data before displaying?

We can create a custom shortcode that returns the enclosed content only if the supplied custom field has a value – to be used with a Shortcode Wrapper component.

Step 1

Install and activate Code Snippets plugin.

Go to Snippets > Add New.

Title: Shortcode to output a custom field only if it has a value

Code:

add_shortcode( 'show_if_has_value', 'func_show_if_has_value' );
/**
 * Add a custom shortcode to display enclosed content only if the supplied advanced custom field has a value.
 *
 * Sample usage: [show_if_has_value fieldname="whatever"]content[/show_if_has_value]
 *
 * @param array $atts An associative array of attributes, or an empty string if no attributes are given.
 * @param string $content The enclosed content.
 * @return void|string Enclosed content if custom field is populated and nothing if otherwise.
 */
function func_show_if_has_value( $atts, $content = '' ) {

	if ( class_exists( 'acf' ) && get_field( $atts['fieldname'] ) ) { // if the custom field has some value
		return $content; // show the enclosed content.
	} else { // otherwise
		return ''; // nothing.
	}

}

Step 2

In the Oxygen editor add a Shortcode Wrapper component.

Full shortcode:

[show_if_has_value fieldname="twitter_url"][/show_if_has_value]

Replace twitter_url with the name of your custom field.

Place other components inside this Shortcode Wrapper and these will be output only if the specified field is populated.

Ex.:

Watch the video at the beginning of this article for a detailed walkthrough.

That’s it!

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