Custom Wordpress field to appear only if completed

时间:2015-07-28 23:28:36

标签: php wordpress

I created a custom-post-type using the Pods plugin. One of the fields is a "website" field. In single-portfolio.php, I have the following code in order to display the website field info.

<p>
<?php $website = get_post_meta($post->ID, 'website', true);?> Website: <a target="_blank" href="<?php echo $website; ?>"><?php echo preg_replace('|https?://|', '', $website ); ?></a><?php $site = preg_replace('{/$}', '', $website); ?>
</p>

2 Questions:

  1. This creates a link url, which when clicked on, the url is preceded by MY site url, and obviously links to a 404 page. What can I change to get ONLY the field's info url?

  2. How can I get the word "Website:" (which precedes the actual field info) to appear in the site ONLY if the field was completed in the backend. Meaning, if this particular project does not have any website info associated with it, the text "Website:" should not appear at all on the site page?

1 个答案:

答案 0 :(得分:0)

要有条件地显示链接(问题2),请检查$website变量是否具有值:

<?php $website=get_post_meta($post->ID,'website',true);
if($website):?>
    Website: <a target="_blank" href="<?php echo $website; ?>"><?php echo preg_replace('|https?://|', '', $website ); ?></a>
<?php $site = preg_replace('{/$}', '', $website);
endif;?>

问题1听起来像您的网址不是以http://开头。如果不是,浏览器将认为它是相对链接。如果您无法提前知道$website字符串是否以http://开头,请实施与此答案中提供的函数类似的函数:https://stackoverflow.com/a/2762083/4772280

将功能添加到functions.php文件后,在为$ website分配值后,将此行添加到代码中:

$website=addhttp($website);