Jon Smith
Jon Smith

Reputation: 314

Setting the value of a javascript variable if null

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>

Upvotes: 1

Views: 187

Answers (2)

TigOldBitties
TigOldBitties

Reputation: 1337

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

Upvotes: 0

jbabey
jbabey

Reputation: 46647

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.

Upvotes: 4

Related Questions