0

I have ACF custom field in posts with the gallery ID. The custom field is stored in wp_postmeta table.

I am trying to execute shortcode on post page with the gallery id assigned to this post.

my code:

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

returns "The gallery was not found!"

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

How to execute the shortcode ont the post page with the ACF value for this post?

I was trying get_field() also but when echoing it returned: "Array to string conversion"

jerri69
  • 25
  • 3

2 Answers2

1

Try this:

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

the_field() (docs) is for directly outputting a value, while get_field() (docs) is for getting the value and for example setting a variable with it.

Edit: I misread your question and saw you already tried this. In that case, try var_dump($gallery_id), look for the returned values, and use the correct array key in returning the gallery ID.

So if the array key is key, you'd use $gallery_id['key'] to output this key.

  • var_dump() returns array(1) { [0]=> int(19557) } so echo do_shortcode('[foogallery id="'. $gallery_id[0] .'"]'); works then! So simple! Thank You. I've spent couple of hours trying... – jerri69 Jan 25 '21 at 22:37
  • @jerri69 No problem, glad it helped. If you can mark my answer as accepted that would be greatly appreciated. Take care! – Bart Klein Reesink Jan 25 '21 at 23:33
0

Based on your other comments, it looks like the_field() (docs) is returning an array, so if you are always expecting an array, you can use reset() (docs) to return the first value in that array.

You can also use the built-in function foogallery_render_gallery rather than do_shortcode.

And it is always good practice to check if the functions exist before you call them. This will help when those plugins are temporarily deactivated, then you will avoid fatal errors.

Try something like this:

//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 );
  }
}
vinnie
  • 333
  • 3
  • 11