【问题标题】:foogallery php shortcode with ID taken from AFC custom field variable does no display从 AFC 自定义字段变量中获取 ID 的 foogallery php 短代码不显示
【发布时间】:2021-04-29 16:44:08
【问题描述】:

我在带有画廊 ID 的帖子中有 ACF 自定义字段。自定义字段存储在 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() 但在回显时返回:“数组到字符串转换”

【问题讨论】:

    标签: php wordpress advanced-custom-fields foogallery


    【解决方案1】:

    试试这个:

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

    the_field() (docs) 用于直接输出一个值,而get_field() (docs) 用于获取该值,例如设置一个变量。

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

    所以如果数组键是key,你会使用$gallery_id['key']来输出这个键。

    【讨论】:

    • var_dump() 返回 array(1) { [0]=> int(19557) } 所以 echo do_shortcode('[foogallery id="'.$gallery_id[0] .'"]') ;然后工作!很简单!谢谢。我已经花了几个小时尝试...
    • @jerri69 没问题,很高兴它有帮助。如果您可以将我的答案标记为已接受,将不胜感激。保重!
    【解决方案2】:

    根据您的其他 cmets,看起来 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 );
      }
    }
    

    【讨论】:

    • 我还不知道reset(),谢谢。
    • 伟大的作品,谢谢。但是 reset() 需要一个数组,所以我认为它必须是 get_field() 而不是 the_field()。
    猜你喜欢
    • 1970-01-01
    • 2013-06-29
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 2020-09-19
    • 1970-01-01
    相关资源
    最近更新 更多