循环外的WordPress自定义字段

时间:2015-02-25 16:12:44

标签: php wordpress advanced-custom-fields

我目前在网站上有一个横幅图片,该图片是通过精选图片提取的。下面的代码可以做到这一点:

if ( has_post_thumbnail() ) {
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
$url = $thumb['0'];

我想将此更改为使用自定义字段,而不是通过高级自定义字段。我创建了一个名为banner_image的自定义字段,其类型为image url。但是我似乎无法使用它。我尝试了以下方法:

方法1

$image = get_field('banner_image', $post->ID);
$url = $image['url'];

方法2

$url = get_field('banner_image', $post->ID);

方法3

$url = get_field('banner_image');

完整的PHP代码:

<?php
// Must be inside a loop.

// This is the bit i cannot get working
if(is_post(991)){
global $wp_query;
$postid = $wp_query->post->ID;
$url = get_post_meta($postid, 'banner_image1', true);
//End the bit that doesn't work
} elseif ( has_post_thumbnail() ) {
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );
$url = $thumb['0'];
}
else {
$bg = array(
'http://domain.co.uk/wp-content/uploads/2014/07/image.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image1.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image2.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image3.jpg',
'http://domain.co.uk/wp-content/uploads/2014/07/image4.jpg'
 ); // array of filenames

 $i = rand(0, count($bg)-1); // generate random number size of the array
  $url = "$bg[$i]"; // set variable equal to which random filename was chosen
 }
?>

有没有人有这样做的方法,我只是在那个特定的帖子上得到一个空白页面。其他帖子工作正常,因此在elseif之后不会破坏代码?

2 个答案:

答案 0 :(得分:0)

尝试这个

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'customField', true);
?>

https://echohelp.wordpress.com/2014/04/28/custom-field-outside-the-loop/

答案 1 :(得分:0)

如果你在循环中,这可行:

$image = get_field('banner_image');
<?php echo $image['url']; ?>