WordPress post gallery php

Using WordPress ‘post_gallery’ PHP filter

The post_gallery WordPress PHP filter allows you to modify the default gallery shortcode output. If the filtered output isn’t empty, it will be used instead of generating the default gallery template.

Usage

add_filter('post_gallery', 'your_custom_function', 10, 3); function your_custom_function($output, $attr, $instance) < // Your custom code here return $output; >

Parameters

  • $output (string) – The gallery output. Default empty.
  • $attr (array) – Attributes of the gallery shortcode.
  • $instance (int) – Unique numeric ID of this gallery shortcode instance.

More information

See WordPress Developer Resources: post_gallery

Examples

Change the default gallery output by creating a custom HTML structure.

add_filter('post_gallery', 'custom_gallery_html', 10, 3); function custom_gallery_html($output, $attr, $instance) < // Retrieve the images from the gallery $ids = explode(',', $attr['ids']); $output = '
'; foreach ($ids as $id) < $image_src = wp_get_attachment_image_src($id, 'thumbnail'); $output .= 'Wordpress post gallery php'; > $output .= '
'; return $output; >

Display image captions below each image in the gallery.

add_filter('post_gallery', 'add_captions_to_gallery', 10, 3); function add_captions_to_gallery($output, $attr, $instance) < $ids = explode(',', $attr['ids']); $output = '
'; foreach ($ids as $id) < $image_src = wp_get_attachment_image_src($id, 'thumbnail'); $image_caption = wp_get_attachment_caption($id); $output .= '
'; $output .= 'Wordpress post gallery php'; $output .= '

' . $image_caption . '

'; $output .= '
'; > $output .= '
'; return $output; >

Add a lightbox feature to the default gallery output.

Create a slider using the gallery images.

add_filter('post_gallery', 'gallery_to_slider', 10, 3); function gallery_to_slider($output, $attr, $instance) < $ids = explode(',', $attr['ids']); $output = ''; foreach ($ids as $id) < $image_src = wp_get_attachment_image_src($id, 'large'); $output .= ''; $output .= ''; $output .= ''; > $output .= ''; return $output; >

Limit the Number of Images Displayed in the Gallery

Restrict the number of images shown in the gallery to a specific count.

add_filter('post_gallery', 'limit_gallery_images', 10, 3); function limit_gallery_images($output, $attr, $instance) < $ids = explode(',', $attr['ids']); $limit = 5; // Set the number of images to display $output = ''; for ($i = 0; $i < $limit && $i < count($ids); $i++) < $id = $ids[$i]; $image_src = wp_get_attachment_image_src($id, 'thumbnail'); $output .= ''; > $output .= ''; return $output; >

Источник

get_post_gallery() │ WP 3.6.0

Получает первую галерею из текста указанной записи/поста. Ищет шорткод в тексте, обрабатывает его и возвращает массив данных картинок галереи. Аналог функции get_post_galleries(), только получает данные первой галереи, а не всех имеющихся.

Хуки из функции

Возвращает

  • массив — Список картинок галереи.
  • строку HTML — Если параметр $html=true то вернет строку — HTML код галереи.
  • false — Если на странице галерея отсутствует.

Использование

get_post_gallery( $post, $html );

$post(число/WP_Post) (обязательный) ID или объект записи в тексте которой нужно найти первую галерею. $html(логический) В данных возвращать готовый HTML галереи или данные галереи в виде ID вложений и ссылок на картинки этих вложений.
По умолчанию: true

Примеры

#1 Получим первую галерею записи 2179

$gal = get_post_gallery( 2179, false ); /* $gal будет содержать Array ( [ids] => 6790,6789,6788 [src] => Array ( [0] => http://wp-kama.ru/wp-content/uploads/2016/02/image12-80x80.png [1] => http://wp-kama.ru/wp-content/uploads/2016/02/image11-80x80.png [2] => http://wp-kama.ru/wp-content/uploads/2016/02/image10-80x80.png ) ) */ $gal = get_post_gallery( 2179, true ); /* $gal будет содержать строку HTML галереи 
*/

Список изменений

Код get_post_gallery() get post gallery WP 6.2.2

function get_post_gallery( $post = 0, $html = true ) < $galleries = get_post_galleries( $post, $html ); $gallery = reset( $galleries ); /** * Filters the first-found post gallery. * * @since 3.6.0 * * @param array $gallery The first-found post gallery. * @param int|WP_Post $post Post ID or object. * @param array $galleries Associative array of all found post galleries. */ return apply_filters( 'get_post_gallery', $gallery, $post, $galleries ); >

Cвязанные функции

Источник

Читайте также:  Base64 encode with javascript

get_post_gallery_images() │ WP 3.6.0

Возвращает все URL картинок первой галереи из указанного текста записи (поста), если галерея в тексте есть.

1 раз — 0.0064108 сек (очень медленно) | 50000 раз — 81.22 сек (очень медленно) | PHP 7.3.12, WP 5.3.2

Возвращает

Использование

get_post_gallery_images( $post );

$post(число/WP_Post) ID/объект записи в ссылки картинок галерей которой нужно получить.
По умолчанию: текущий пост

Примеры

#1 Получим список всех SRC картинок из первой галереи поста 2179

$gal = get_post_gallery_images(2179); /* $gal будет содержать Array ( [0] => http://wp-kama.ru/wp-content/uploads/2016/02/image12-80x80.png [1] => http://wp-kama.ru/wp-content/uploads/2016/02/image11-80x80.png [2] => http://wp-kama.ru/wp-content/uploads/2016/02/image10-80x80.png ) */

#2 Получим список всех SRC картинок из первой галереи поста в редакторе Гутенберг

В блочном редакторе (Гутенберг) галерея имеет другой вид — не шорткод, поэтому функция get_post_gallery_images() вернет пустой массив.

Эта проблема известна и описана в тикете #43826, но решение станет частью ядра лишь только в будущем, точной даты нет.

/** * Возвращает все URL картинок первой галереи из указанного текста записи. * Вернёт результат, если галлерея есть и вставлена как блок (Гутенберг). * * @param int|WP_Post $post * * @return array */ function get_post_block_gallery_images( $post = 0 ) < $post = get_post( $post ); // Запись не нашлась - возвращаем пустой массив if ( ! is_a( $post, 'WP_Post' ) ) < return []; >// Блок "Галерея" не нашелся - возвращаем пустой массив if ( ! has_block( 'gallery', $post->post_content ) ) < return []; >// Ищем все блоки в контенте $post_blocks = parse_blocks( $post->post_content ); // Перебираем все блоки в поисках нужного foreach ( $post_blocks as $block ) < // Ищем блок "Галерея" с переданными ID изображений if ( $block['blockName'] === 'core/gallery' && ! empty( $block['attrs']['ids'] ) ) < return array_map( function ( $image_id ) < // Получаем ссылку на оригинал изображения return wp_get_attachment_image_url( $image_id, 'full' ); >, $block['attrs']['ids'] ); > > // Если блок "Галерея" не нашелся - возвращаем пустой массив return []; >

Заметки

Список изменений

Код get_post_gallery_images() get post gallery images WP 6.2.2

function get_post_gallery_images( $post = 0 )

Источник

WordPress post gallery php

Image galleries are the best way to showcase your pictures on your WordPress sites. WordPress bundles the Create Gallery feature by default in the media uploader which allows you to create a simple gallery.

Note: Before adding a gallery, you must have images in your media library. Otherwise, you need to upload the images into the library and can proceed on gallery creation.

The Gallery feature allows you to add one or more image galleries to your posts and pages using a simple Shortcode.

The basic form of gallery shortcode is:

Tip:
If you use the shortcode without using the ids argument in your post or page, only images that are “attached” to that post or page will be displayed.

If you need to add multiple images with ID’s, use the following sample shortcode

//Note: 10, 205, 552 and 607 are the IDs of respected image. 

Tip:
NOTE: find the proper IDs of the images for the gallery. Go to Media library and click on the respected image and ID will appear on the URL.

Читайте также:  Ассоциативный массив данных php

To use the shortcode from the template file, use the do_shortcode() function. Insert the following code into your template file:

If you need to use the shortcode with IDs, insert the following code in your template file:

Usage

There are may options that may be specified using the below syntax:

If you want to print the gallery directly on the template file, use `do_shortcode() ` function like below:

If you need to filter the shortcodes, the following example gives you some tips

// Note: 'the_content' filter is used to filter the content of the // post after it is retrieved from the database and before it is // printed to the screen.

Supported Options

Gallery Shortcodes supports the basic options which are listed below:

Orderby

‘orderby’ specifies the order the thumbnails show up. The default order is ‘menu_order’.

  • menu_order: You can reorder the images in the Gallery tab of the Add Media popup
  • title: Order by the title of the image in the Media Library
  • post_date: Sort by date/time
  • rand: Order randomly
  • ID: Specify the post ID

Order

order specify the sort order used to display thumbnail; ASC or DESC. For Example, to sort by ID and DESC:

If you need to print it on template file, use the do_shortcode() function;

columns

The Columns options specify the number of columns in the gallery. The default value is 3.
If you want to increase the number of column in the galley, use the following shortcode.

If you need to print it on your template file, use the do_shortcode() function;

IDs

The IDs option on the gallery shortcode loads images with specific post IDs.

If you want to display the attached image with the specific post ID, follow the following code example.

// Note: remove each space between brackets and 'gallery' and brackets and `123"`. //Here "123" stands for the post IDs. If you want to display more than //one ID, separate the IDs by a comma `,`. [ gallery ]

Use ‘do_shortcode’ function to print the gallery with IDs on template files like below:

// Note: remove each space between brackets and 'gallery' and brackets and `123"`.

Size

For example, to display a gallery of medium sized images:

Some advanced options are also available on Gallery shortcodes.

itemtag

The name of the HTML tag used to enclose each item in the gallery. The default is “dl”.

icontag

The name of the HTMLtag used to enclose each thumbnail icon in the gallery. The default is “dt”.

captiontag

The name of the HTML tag used to enclose each caption. The default is “dd”.

You are allowed to change the defaults.

Specify where you want the image to link. The default value links to the attachment’s permalink. Options:

Include

Include allows you to insert an “array” of comma separated attachment IDs to show only the images from these attachments.

Exclude

Exclude callows you to insert an “array” of comma separated attachment IDs to not show the images from these attachments. Please note that include and exclude cannot be used together.

References

For more technical details take a reference from below links

Источник

get_post_galleries() │ WP 3.6.0

Получает все галереи из текста указанной записи/поста. Ищет шорткоды в тексте, обрабатывает их и возвращает массив данных картинок галерей.

Читайте также:  Isolation forest python пример
Хуки из функции

Возвращает

Массив . Список картинок галереи или нескольких галерей. Если параметр $html=true то массив будет содержать готовый HTML код каждой галереи.

Использование

get_post_galleries( $post, $html );

$post(число/WP_Post) (обязательный) ID или объект записи в тексте которой нужно найти галереи. $html(логический) В данных возвращать готовый HTML галереи или данные галереи в виде ID вложений и ссылок на картинки.
По умолчанию: true

Примеры

#1 Получим все галере записи 2179

Этот пример показывает как работает функция. Предполагается что в тексте записи 2179 присутствуют 2 галереи — 2 шорткода :

$gal = get_post_galleries(2179, false); /* $gal будет равно Array ( [0] => Array ( [ids] => 6790,6789,6788 [src] => Array ( [0] => http://wp-kama.ru/wp-content/uploads/2016/02/image12-80x80.png [1] => http://wp-kama.ru/wp-content/uploads/2016/02/image11-80x80.png [2] => http://wp-kama.ru/wp-content/uploads/2016/02/image10-80x80.png ) ) [1] => Array ( [ids] => 6762,6761,6760 [src] => Array ( [0] => http://wp-kama.ru/wp-content/uploads/2016/02/image008-80x80.jpg [1] => http://wp-kama.ru/wp-content/uploads/2016/02/image007-80x80.jpg [2] => http://wp-kama.ru/wp-content/uploads/2016/02/image006-80x80.jpg ) ) ) */ $gal = get_post_galleries(25, true); /*$gal будет равно Array ( [0] => 
[1] =>
) */

Список изменений

Код get_post_galleries() get post galleries WP 6.2.2

function get_post_galleries( $post, $html = true ) < $post = get_post( $post ); if ( ! $post ) < return array(); >if ( ! has_shortcode( $post->post_content, 'gallery' ) && ! has_block( 'gallery', $post->post_content ) ) < return array(); >$galleries = array(); if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) < foreach ( $matches as $shortcode ) < if ( 'gallery' === $shortcode[2] ) < $srcs = array(); $shortcode_attrs = shortcode_parse_atts( $shortcode[3] ); if ( ! is_array( $shortcode_attrs ) ) < $shortcode_attrs = array(); >// Specify the post ID of the gallery we're viewing if the shortcode doesn't reference another post already. if ( ! isset( $shortcode_attrs['id'] ) ) < $shortcode[3] .= ' . (int) $post->ID . '"'; > $gallery = do_shortcode_tag( $shortcode ); if ( $html ) < $galleries[] = $gallery; >else < preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER ); if ( ! empty( $src ) ) < foreach ( $src as $s ) < $srcs[] = $s[2]; >> $galleries[] = array_merge( $shortcode_attrs, array( 'src' => array_values( array_unique( $srcs ) ), ) ); > > > > if ( has_block( 'gallery', $post->post_content ) ) < $post_blocks = parse_blocks( $post->post_content ); while ( $block = array_shift( $post_blocks ) ) < $has_inner_blocks = ! empty( $block['innerBlocks'] ); // Skip blocks with no blockName and no innerHTML. if ( ! $block['blockName'] ) < continue; >// Skip non-Gallery blocks. if ( 'core/gallery' !== $block['blockName'] ) < // Move inner blocks into the root array before skipping. if ( $has_inner_blocks ) < array_push( $post_blocks, . $block['innerBlocks'] ); >continue; > // New Gallery block format as HTML. if ( $has_inner_blocks && $html ) < $block_html = wp_list_pluck( $block['innerBlocks'], 'innerHTML' ); $galleries[] = '
' . implode( ' ', $block_html ) . '
'; continue; > $srcs = array(); // New Gallery block format as an array. if ( $has_inner_blocks ) < $attrs = wp_list_pluck( $block['innerBlocks'], 'attrs' ); $ids = wp_list_pluck( $attrs, 'id' ); foreach ( $ids as $id ) < $url = wp_get_attachment_url( $id ); if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) < $srcs[] = $url; >> $galleries[] = array( 'ids' => implode( ',', $ids ), 'src' => $srcs, ); continue; > // Old Gallery block format as HTML. if ( $html ) < $galleries[] = $block['innerHTML']; continue; >// Old Gallery block format as an array. $ids = ! empty( $block['attrs']['ids'] ) ? $block['attrs']['ids'] : array(); // If present, use the image IDs from the JSON blob as canonical. if ( ! empty( $ids ) ) < foreach ( $ids as $id ) < $url = wp_get_attachment_url( $id ); if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) < $srcs[] = $url; >> $galleries[] = array( 'ids' => implode( ',', $ids ), 'src' => $srcs, ); continue; > // Otherwise, extract srcs from the innerHTML. preg_match_all( '#src=([\'"])(.+?)\1#is', $block['innerHTML'], $found_srcs, PREG_SET_ORDER ); if ( ! empty( $found_srcs[0] ) ) < foreach ( $found_srcs as $src ) < if ( isset( $src[2] ) && ! in_array( $src[2], $srcs, true ) ) < $srcs[] = $src[2]; >> > $galleries[] = array( 'src' => $srcs ); > > /** * Filters the list of all found galleries in the given post. * * @since 3.6.0 * * @param array $galleries Associative array of all found post galleries. * @param WP_Post $post Post object. */ return apply_filters( 'get_post_galleries', $galleries, $post ); >

Cвязанные функции

Источник

Оцените статью