0

I would like to create a shortcode that displays the image from an ACF custom field which currently has the return format set to the Image ID. The shortcode needs to accept a post_id so it can get the field from a certain page.

So the shortcode would be:

[acf_featured_item post_id="88"]

I am aware that there is an ACF shortcode available, but there is already another location which is dependant on the return format as ID. So I cannot change this.

My Current code is:

function acf_featured_item_shortcode( $atts ) {
// Attributes
$atts = shortcode_atts(
    array(
        'post_id' => '',
    ),
    $atts
);
$image = get_field('featured_item', $post_id );
$size = 'medium'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
$output = wp_get_attachment_image( $image, $size, "", array( "class" => "mx-auto d-block" ));
} 
return $output;
}
add_shortcode( 'acf_featured_item', 'acf_featured_item_shortcode' );

But this only works when you are on the page for that id. How do I get this shortcode to work on any page with any post_id input?

1
  • And what exactly is your question? Developing shortcodes is described in the Plugin Handbook. Please edit your question to make clear what the result should be, what it currently is and where exactly you're having troubles.
    – kero
    Commented Nov 7, 2019 at 12:48

1 Answer 1

3

It's because you have forgot to use $atts['post_id'] please find below code.

function acf_featured_item_shortcode( $atts ) {
    // Attributes
    $atts = shortcode_atts(
        array(
            'post_id' => '',
        ),
        $atts
    );
    $post_id = $atts['post_id'];
    $image = get_field('featured_item', $post_id );
    $size = 'medium'; // (thumbnail, medium, large, full or custom size)
    if( $image ) {
        $output = wp_get_attachment_image( $image, $size, "", array( "class" => "mx-auto d-block" ));
    } 
    return $output;
}
add_shortcode( 'acf_featured_item', 'acf_featured_item_shortcode' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.