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');
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');
Share
Improve this question
edited Oct 20, 2020 at 6:50
Mayeenul Islam
12.9k21 gold badges85 silver badges169 bronze badges
asked Oct 19, 2020 at 16:29
Muhammad MuazzamMuhammad Muazzam
1762 silver badges16 bronze badges
2
|
1 Answer
Reset to default 0I 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/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" />';
}
}
$gallery = '';
before the lineif ($images) {
and shouldreturn $gallery
outside theif
conditional. If the code still doesn't work, you can go with output buffering withob_start();
at the beginning of the output andreturn ob_get_clean();
when the function ends. – Mayeenul Islam Commented Oct 20, 2020 at 6:52