简体   繁体   English

循环外的 WordPress 自定义字段

[英]WordPress custom field outside of loop

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.我创建了一个名为 banner_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 代码:

<?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 ?其他帖子工作正常,所以它不会在elseif之后破坏代码?

try this one 试试这个

<?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/ https://echohelp.wordpress.com/2014/04/28/custom-field-outside-the-loop/

If you are inside the loop, this works: 如果你在循环中,这可以工作:

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

You can use您可以使用

get_field('banner_image', get_the_ID() );

or或者

get_field('banner_image', get_queried_object_id() );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM