foogallery php 带有从 AFC 自定义字段变量中获取的 ID 的简码不显示

foogallery php shortcode with ID taken from AFC custom field variable does no display

我在 post 中有 ACF 自定义字段和图库 ID。自定义字段存储在 wp_postmeta table.

我正在尝试在 post 页面上执行短代码,其中画廊 ID 分配给此 post。

我的代码:

$post = get_post();
$gallery_id = the_field('gallery', $post->ID );
echo do_shortcode('[foogallery id="'. $gallery_id .'"]');

returns“找不到图库!”

echo($gallery_id); // returns 19557
echo do_shortcode('[foogallery id="19557"]'); // works well

如何使用 post 的 ACF 值在 post 页面上执行短代码?

我也在尝试 get_field() 但当回显时它返回:“数组到字符串的转换”

试试这个:

$gallery_id = get_field('gallery', $post->ID );

the_field() (docs) is for directly outputting a value, while get_field() (docs) 用于获取值,例如用它设置变量。

编辑:我误读了你的问题,看到你已经试过了。在这种情况下,请尝试 var_dump($gallery_id),查找返回值,并在返回图库 ID 时使用正确的数组键。

因此,如果数组键是 key,您将使用 $gallery_id['key'] 来输出此键。

根据您的其他评论,看起来 the_field() (docs) is returning an array, so if you are always expecting an array, you can use reset() (docs) 到 return 该数组中的第一个值。

您也可以使用内置函数 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 );
  }
}