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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示