Only show images/attachments within the gallery?

2019-04-17 04:21发布

When i create a page, add a gallery, and browse this gallery on the front-end it will browse all the attachments that are associated with that page, instead of just the images within that gallery. Is there a way to filter all the other attachments and only show the images within a certain gallery? So that, for instance, when I delete the gallery and add a new gallery on the same page > only the new gallery is shown?

Any ideas?

标签: wordpress
1条回答
孤傲高冷的网名
2楼-- · 2019-04-17 04:58

This might not be the most elegant way, but i've found it very usefull.

Passing a post ID to the function below will load a gallery from the post_content of that post. So you would create a gallery and insert it into your post content, then in the template you run this function and will be returned with an array of attachments in that gallery which you are free to to whatever with, i.e slideshows and the likes.

function wp_load_gallery($post_id) {
  $post = get_post( $post_id );
  $regx = '/' . get_shortcode_regex() . '/';
  preg_match( $regx, $post->post_content, $matches );
  $ids = shortcode_parse_atts( $matches[3] );

  $gallery = array( );
  foreach( explode( ',', $ids['ids'] ) as $id ) {
    if($id) {
      $gallery[] = get_post( $id );
    }
  } 

  return $gallery;
}

Note that the shortcode is not cut from the content, so when you display the content you should run it through the strip_shortcodes function, i.e:

echo strip_shortcodes( get_the_content() );

This allows you to update the gallery whenever you want with whatever you want.

EDIT:

To simply display all images:

$gallery = wp_load_gallery($YOUR_POST_ID);
foreach($gallery as $image) {
  echo wp_get_attachment_image($image->ID);
}
查看更多
登录 后发表回答