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

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"
Answer
Solution:
Try this:
$gallery_id = get_field('gallery', $post->ID );
the_field()
(docs) is for directly outputting a value, whileget_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, tryvar_dump($gallery_id)
, look for the returned values, and use the correct array key in returning the gallery ID.
So if the array key iskey
, you'd use$gallery_id['key']
to output this key.
Answer
Solution:
Based on your other comments, it looks likethe_field()
(docs) is returning an array, so if you are always expecting an array, you can usereset()
(docs) to return the first value in that array.
You can also use the built-in functionfoogallery_render_gallery
rather thando_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 );
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: illuminate\http\exceptions\posttoolargeexception
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.