-2

I can't use shortcode with foreach. It gives me syntax error. Where i am wrong?

function create_galeri_shortcode($atts) {

$atts = shortcode_atts(
    array(
    ),
    $atts,
    'galeri'
);

if ( has_post_format( 'gallery' )) {
    $images = get_post_meta(get_the_ID(), 'vdw_gallery_id', true);
    if($images) {
        $out = '<div id="lightgallery">'.
        foreach ($images as $imageid) {
        $altyazi = get_post_meta( get_the_ID(), '_wp_attachment_image_alt', true ).'
        <a href="'.wp_get_attachment_url($imageid, 'large').'" data-sub-html=".caption">
            <img src="'.wp_get_attachment_url($imageid, 'thumbnail').'" alt="'.$altyazi.'">
            <div class="caption">
                <h4>'.$altyazi.'</h4><p>'.wp_get_attachment_caption($imageid).'</p>
            </div>
        </a>
        '.}.'
        </div>';
    }
}
return $out;
}
add_shortcode( 'galeri_mm', 'create_galeri_shortcode' );
3
  • you cannot create a string like that. it's a PHP question and not WordPress related.
    – mmm
    Apr 30, 2018 at 5:41
  • So i can't asq this question here right?
    – wpdev
    Apr 30, 2018 at 5:44
  • syntax errors are simple to fix, if you do not understand what they mean, you should ask about it, but again this is the wrong place for such questions Apr 30, 2018 at 6:57

1 Answer 1

2

You're trying to concatenate a foreach statement in to a string, which can't be done... You need to add the output that you need to your existing string, not concatenate it

function create_galeri_shortcode( $atts ) {

    $atts = shortcode_atts(
        array(
        ),
        $atts,
        'galeri'
    );

    if ( has_post_format( 'gallery' ) ) {
        $images = get_post_meta( get_the_ID(), 'vdw_gallery_id', true );
        if( $images ) {
            $out = '<div id="lightgallery">'.
            foreach ($images as $imageid) {
                $altyazi = get_post_meta( get_the_ID(), '_wp_attachment_image_alt', true );
                $out .= '<a href="'.wp_get_attachment_url($imageid, 'large').'" data-sub-html=".caption">';
                    $out .= '<img src="'.wp_get_attachment_url($imageid, 'thumbnail').'" alt="'.$altyazi.'">';
                    $out .= '<div class="caption">';
                        $out .= '<h4>'.$altyazi.'</h4>'; 
                        $out .= '<p>'.wp_get_attachment_caption( $imageid ).'</p>';
                    $out .= '</div>';
                $out .= '</a>';
            }
            $out .= '</div>';
        }
    }
return $out;
}
add_shortcode( 'galeri_mm', 'create_galeri_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.