我有ACF自定义字段与画廊ID的帖子。自定义字段存储在wp_postmeta表中。
我正试图在分配给这篇文章的画廊id的帖子页面上执行短代码。
我代码:
$post = get_post();
$gallery_id = the_field('gallery', $post->ID );
echo do_shortcode('[foogallery id="'. $gallery_id .'"]');
返回"图库未找到!">
echo($gallery_id); // returns 19557
echo do_shortcode('[foogallery id="19557"]'); // works well
如何在帖子页面上执行该帖子的ACF值?
我也在尝试get_field(),但当它返回时返回:"数组到字符串转换">
试试这个:
$gallery_id = get_field('gallery', $post->ID );
the_field()
(docs)用于直接输出一个值,而get_field()
(docs)用于获取该值,例如用它设置一个变量。
var_dump($gallery_id)
,寻找返回值,并使用正确的数组键返回画廊ID。
因此,如果数组键是key
,您将使用$gallery_id['key']
来输出该键。
根据您的其他评论,看起来the_field()
(docs)正在返回一个数组,所以如果您总是期望一个数组,您可以使用reset()
(docs)返回该数组中的第一个值。
您也可以使用内置函数foogallery_render_gallery
而不是do_shortcode
。
在调用函数之前检查函数是否存在总是好的做法。这将有助于当这些插件暂时禁用,然后你将避免致命的错误。
试试这样写:
//get the current post
$post = get_post();
//check to make sure ACF plugin is activated
if ( function_exists( 'the_field' ) ) {
//get the field value from ACF
$gallery_id = the_field( 'gallery', $post->ID );
//we are expecting an array, so use reset to rewind the pointer to the first value
reset( $gallery_id );
//check to make sure FooGallery is activated
if ( function_exists( 'foogallery_render_gallery') ) {
//finally, render the gallery
foogallery_render_gallery( $gallery_id );
}
}