• Resolved morgyface

    (@morgyface)


    I’m pulling my hair out and would really appreciate some help.

    I want a PHP/WP expression that basically says “If ANY custom fields exist then display this title”.

    I have found lots of posts relating to “If a specific custom field exists then do this”… but none for ANY.

    Please help before I throw my entire computer out the window and urinate on it.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    🏳️‍🌈 Advisor and Activist

    That would be expensive.

    As you’ve noticed, the commands like if(get_post_meta($post->ID, 'CustomField', true) are pretty darned specific, and that’s for a reason. There’s no way for the post meta to know what is and isn’t a ‘custom’ field. It’s just data.

    Do you have a set list of what the custom fields MIGHT be?

    Thread Starter morgyface

    (@morgyface)

    @ipstenu No, they will relate to the dimensions of a product but are like to vary…

    This seems to work:

    <?php
    	// Get the custom fields for this post
    	$custom_fields = get_post_custom(); 
    
    	// Set has_custom to false by default
    	$has_custom = false;
    
    	/*
    	 * Loop thorugh a see if any DONT begin with an underscore
    	 * (posts by default have some meta, but prefixed with _)
    	 */
    	foreach($custom_fields as $k => $field) {
    		if('_' != substr($k,0,1)) {
    			$has_custom = true;	// Set to true, there IS a custom field
    		}
    	}
    
    	// Do some stuff if there is a custom field
    	if($has_custom) {
    		echo '<h2>This post has custom field</h2>';
    	}
    ?>
    Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    🏳️‍🌈 Advisor and Activist

    No, they will relate to the dimensions of a product but are like to vary..

    Wait really? Cause … I was pretty sure dimensions are static by NAME if not value.

    Height, width, depth. After that you get into time, which is the FOURTH dimension, but still, if you keep the name of the custom field consistant, there you go.

    Thread Starter morgyface

    (@morgyface)

    @ipstenu the problem is the NAME will be defined by the client, I need it to be fool-proof, e.g she could enter, “Depth” instead of “Width” or “Tall” instead of “Height” she could spell things incorrectly, I have no way of guaranteeing consistency, which is why it’s sensible to use “If ANY custom fields exist”

    Since you can use “the_meta()” I presumed you’d also be able to say IF there is the_meta() then do this… but strangely you cannot!

    Anyway thanks to @robmcvizzle on Twitter, I got the code I needed, but wow so complicated for something so simple!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Display title if ANY custom fields exist’ is closed to new replies.