admin管理员组文章数量:1420205
I need opposite of this:
<?php if ( get_post_meta($post->ID, 'price_list_category1', true) ) : ?>style="display:none;"<?php endif; ?>
In other words I want style="display:none;"
only when meta data doesn't exist.
I thought it would be straightforward like if ( get_post_meta($post->ID, 'price_list_category1', true
but this true/false turns out to be a completely different stuff.
any ideas?
Thank you.
I need opposite of this:
<?php if ( get_post_meta($post->ID, 'price_list_category1', true) ) : ?>style="display:none;"<?php endif; ?>
In other words I want style="display:none;"
only when meta data doesn't exist.
I thought it would be straightforward like if ( get_post_meta($post->ID, 'price_list_category1', true
but this true/false turns out to be a completely different stuff.
any ideas?
Thank you.
Share Improve this question asked Jun 26, 2012 at 19:32 user8842user88424 Answers
Reset to default 10You could use the empty
function inside your if
as such :
<?php if( empty( get_post_meta( $post->ID, 'price_list_category1', true ) ) ) : ?>style="display:none;"<?php endif; ?>
The above returns an error, you should assign the return value to a variable. See my edit below.
Warning
empty
might not be the best option depending on the values you store in the meta. Values like false
, 0
etc... will be considered empty.
Check the PHP manual for the full list of values that are considered empty.
Edit
You can try assigning the meta to a variable, and using that in the if
statement.
<?php
$price_list = get_post_meta( $post->ID, 'price_list_category1', true );
?>
And then...
if( empty( $price_list) ) : ?>style="display:none"<?php endif; ?>
You can use metadata_exists();
(worked for me)for checking for any post meta and the do whatever you want.
// Check and get a post meta
if ( metadata_exists( 'post', $post_id, '_meta_key' ) ) {
$meta_value = get_post_meta( $post_id, '_meta_key', true );
}
I found this via searching for a solution myself, but it dawned on me the answer is very simple. You simply need to check if the value is empty, if it is then echo nothing - if it has content, then display the content - the code i used is below and can be tailored accordingly to anyone who needs to use it.
<?php $meta = get_post_meta( get_the_ID(), 'page-sub-title', true );
if ($meta == '') {
echo ' ';
} else {
echo '<h2>' . $meta . '</h2>';
}
?>
if( ! in_array( 'given_key', get_post_custom_keys($post_id) ) ) {}
Here it is written: https://developer.wordpress/reference/functions/get_post_meta/#user-contributed-notes
get_post_custom_keys Returns an array containing the keys of all custom fields of a particular post or page. For me, this is the best solution :)
本文标签: post metaif getpostmeta is empty do something
版权声明:本文标题:post meta - if get_post_meta is empty do something 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745323865a2653502.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论