dousikuai5417 2015-02-25 16:12 采纳率: 0%
浏览 61
已采纳

循环外的WordPress自定义字段

I currently have a banner image on a site which is pulled in via the featured image. The code below that does this works:

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

I would like to change this to use a custom field instead via Advanced Custom Fields. I have made a custom field called banner_image with the type as image url. I cannot seem to get this working however. I have tried the following methods:

Method 1

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

Method 2

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

Method 3

$url = get_field('banner_image');

Full PHP Code:

<?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
 }
?>

Does anyone have a method for doing this, I am just getting a blank page on that particular post. Other posts work fine so it isn't breaking the code after elseif?

  • 写回答

2条回答 默认 最新

  • dsp1836 2015-02-26 22:02
    关注

    If you are inside the loop, this works:

    $image = get_field('banner_image');
    <?php echo $image['url']; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导