我目前在一个网站上有一个横幅图片,它是通过特色图片拉进来的。下面的代码可以做到这一点:
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
之后的代码?
如果你在循环中,这是有效的:
$image = get_field('banner_image');
<?php echo $image['url']; ?>
试试这个
<?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/
您可以使用
get_field('banner_image', get_the_ID() );
或
get_field('banner_image', get_queried_object_id() );