1

I am setting 3 global variables to the values of my posts meta data. I would like to understand how to set a default value for each variable if none is returned.

<script type="text/javascript">
var JprettyAd = '<?php echo get_post_meta($post->ID, 'prettyAd', true); ?>';
var JprettyName = '<?php get_post_meta($post->ID, 'prettyName', true); ?>';
var JprettyLink = '<?php get_post_meta($post->ID, 'prettyLink', true); ?>';
</script>
4
  • 1
    If 'none is returned' from..? php or javascript? Commented Aug 27, 2012 at 15:21
  • Your 3'rd variable value definitely has syntax errors.. Commented Aug 27, 2012 at 15:23
  • 1
    You can't, if php returns null, the value will be 'null', a string is never false or null, unless the php returns an empty string. If the ouput looks like this: var JprettyAd = '';, you could can simply add the default operator: var JprettyAd = '<?php echo get_post_meta($post->ID, 'prettyAd', true); ?>' || 'defaultString'; Commented Aug 27, 2012 at 15:23
  • better run that php output through json_encode(), unless you enjoy having your JS code injected and killed due to syntax errors. Commented Aug 27, 2012 at 15:49

2 Answers 2

4
var JprettyAd = <?php echo get_post_meta($post->ID, 'prettyAd', true); ?> ||
    'someDefault';

Note this will use the 'someDefault' value if PHP returns any "falsey" value: null, undefined, '', 0, or NaN.

See the section labeled "Default Assignments" here.

Sign up to request clarification or add additional context in comments.

2 Comments

You should quote the <php..> otherwise it may be interpreted as a variable name and error out. Unless you're sure that the value is a number.
Thank you. With a small tweak this works perfectly. All that was need was to add single quotes around php and change the key quotes to double.
0

get_post_meta returns an empty array if not found so you can do

<?php $response = get_post_meta($post->ID, 'prettyAd', true); ?>
var JprettyAd = <?php echo ($response ?: $defaultValue); ?>;

because empty arrays in php are evaluated as false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.