0

I'm detecting if the user has a gallery in his post:

$gallery = get_post_gallery( $post->ID, False );
$gallery_images = explode( ',', $gallery['ids'] );

And at times I'd like to see how many columns it has:

var_dump( $gallery['columns'] );

This works for 2 columns, it returns 2 but if I were to set the columns to 3, it breaks, throwing the error:

<b>Notice</b>:  Undefined index: columns in <b>C:\file.php</b> on line <b>45</b>

Note that 4, 5 columns work just fine, but 3 won't. This only happens when there's a second gallery in the post.

How is this possible?

3
  • 1
    I just tested this and yes, I can also see this behaviour! My first thought was that it has to do with the default setting. 3 columns seems to be the default gallery column count in WordPress. Sorry I have no fix for you in the moment.
    – LWS-Mo
    Jun 18 '18 at 12:53
  • @LWS-Mo Great. At least I know it's a bug.
    – coolpasta
    Jun 18 '18 at 13:14
  • I found that if you select the default 3 columns, the column key dont exists in the array. So you could check if the array-key column exists. See my answer...
    – LWS-Mo
    Jun 18 '18 at 13:23
3

OK, I just tested this a little further. Indeed, if you select 3 columns (the default WP gallery column count) and do a var_dump( $gallery ); you will see that there is no column key in the array. (like for example with 4 columns ["columns"]=> "4").
You can maybe do something like this:

$gallery = get_post_gallery( $post->ID, false );

if (array_key_exists( 'columns', $gallery )) {
    echo $gallery['columns'];
} else {
    echo 'default WP 3 columns';
}
5
  • $columns = isset( $gallery['columns'] ) ? $gallery['columns'] : '3'; //Fix Did it for me.
    – coolpasta
    Jun 18 '18 at 13:28
  • @coolpasta oh yes, good idea :)
    – LWS-Mo
    Jun 18 '18 at 13:52
  • @coolpasta isset( $gallery['columns'] ) will cause notices on some PHP versions... Jun 18 '18 at 16:42
  • @KrzysiekDróżdż I only need to support 5.4, 5.3 if I feel nice. Can you explain further?
    – coolpasta
    Jun 19 '18 at 8:28
  • @coolpasta what you want to check is array_key_exists - it’s not the same as isset( $array[$key] ). Jun 19 '18 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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