0

Written the following code in a custom file inside the theme folder and called it via functions.php but at page [product_first_img] shows shortcode text, not output.

function gal_first_shortcode($atts, $content = null)
{

    extract(shortcode_atts(array(
        'size' => ''
    ), $atts));

    $image_size = 'medium';
    if ($size = !'') {
        $image_size = $size;
    }

    $images = get_children(
        array(
            'post_parent' => get_the_ID(),
            'post_type' => 'attachment',
            'numberposts' => 1,
            'post_mime_type' => 'image',
            'orderby' => 'menu_order',
        )
    );

    if ($images) {
        $gallery = '';
        foreach ($images as $image) {
            $gallery .= wp_get_attachment_image($image->ID, $image_size);
        }
        $gallery .= '';
        return $gallery;
    }
}

add_shortcode('product_first_img', 'gal_first_shortcode');
2
  • 1
    The shortcode is working fine in my local environment. Except for the attachment things I didn't test. Apart from that, you should initiate $gallery = ''; before the line if ($images) { and should return $gallery outside the if conditional. If the code still doesn't work, you can go with output buffering with ob_start(); at the beginning of the output and return ob_get_clean(); when the function ends. Commented Oct 20, 2020 at 6:52
  • @MayeenulIslam I have put above code in plugin and its working previously is was coded inside functions.php file Commented Oct 20, 2020 at 9:22

1 Answer 1

0

I change the array in get_children() and foreach loop with below reference url and code work fine. please check the argument that you have passed also use echo statement like they shown in the example.

reference url : https://developer.wordpress.org/reference/functions/get_children/

let me know result or errors

$args = array(
    'posts_per_page' => 1,
    'order'          => 'ASC',
    'post_mime_type' => 'image',
    'post_parent'    => $post_id,
    'post_status'    => null,
    'post_type'      => 'attachment',
);

$attachments = get_children( $args );

if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );
        echo '<img src="' . esc_url( wp_get_attachment_thumb_url( $attachment->ID ) ) . '" class="current" />';
    }
}

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.