Пользовательский HTML-код галереи работает только тогда, когда изображения прикреплены к сообщению/странице


Я изменил html-код своей галереи с помощью крючка posts_gallery таким же образом, как показано здесь: Как настроить вывод шорткода галереи изображений WP из плагина?

Я скопировал последний код с wordpress и изменил переменную $output, чтобы изменить свой html. Проблема в том, что это работает только для изображений, прикрепленных к соответствующей странице. Я хочу использовать изображения с других страниц или которые уже были загружены в галереи.

Галереи создаются с помощью короткого кода с помощью окна мультимедиа и выглядят следующим образом: [идентификаторы галереи="1,2,3,4,5"]. Я пытался заменить идентификаторы на include, но это не работает, и я получаю код по умолчанию, отличный от моего пользовательского вывода html.

Вот вывод моей пользовательской галереи:

function my_gallery_shortcode( $output = '', $atts, $content = false, $tag = false ) {
$return = $output; // fallback

// retrieve content of your own gallery function
$my_result = get_my_gallery_content( $atts );

// boolean false = empty, see http://php.net/empty
if( !empty( $my_result ) ) {
    $return = $my_result;
}

return $return;
}

add_filter( 'post_gallery', 'my_gallery_shortcode', 10, 4 );



function get_my_gallery_content ( $atts ) {

global $post;
// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
if ( isset( $attr['orderby'] ) ) {
    $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
    if ( !$attr['orderby'] )
        unset( $attr['orderby'] );
}

$html5 = current_theme_supports( 'html5', 'gallery' );
extract(shortcode_atts(array(
    'order'      => 'ASC',
    'orderby'    => 'menu_order ID',
    'id'         => $post ? $post->ID : 0,
    'itemtag'    => $html5 ? 'figure'     : 'dl',
    'icontag'    => $html5 ? 'div'        : 'dt',
    'captiontag' => $html5 ? 'figcaption' : 'dd',
    'columns'    => 3,
    'size'       => 'thumbnail',
    'include'    => '',
    'exclude'    => '',
    'link'       => '',
), $attr, 'gallery'));

$id = intval($id);
if ( 'RAND' == $order )
    $orderby = 'none';

if ( !empty($include) ) {
    $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

    $attachments = array();
    foreach ( $_attachments as $key => $val ) {
        $attachments[$val->ID] = $_attachments[$key];
    }
} elseif ( !empty($exclude) ) {
    $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
    $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}

if ( empty($attachments) )
    return '';

if ( is_feed() ) {
    $output = "\n";
    foreach ( $attachments as $att_id => $attachment )
        $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
    return $output;
}

$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$icontag = tag_escape($icontag);
$valid_tags = wp_kses_allowed_html( 'post' );
if ( ! isset( $valid_tags[ $itemtag ] ) )
    $itemtag = 'dl';
if ( ! isset( $valid_tags[ $captiontag ] ) )
    $captiontag = 'dd';
if ( ! isset( $valid_tags[ $icontag ] ) )
    $icontag = 'dt';

$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';

$selector = "gallery-{$instance}";

$gallery_style = $gallery_div = '';

/**
 * Filter whether to print default gallery styles.
 *
 * @since 3.1.0
 *
 * @param bool $print Whether to print default gallery styles.
 *                    Defaults to false if the theme supports HTML5 galleries.
 *                    Otherwise, defaults to true.
 */
if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
    $gallery_style = "
    <style type='text/css'>
        #{$selector} {
            margin: auto;
        }
        #{$selector} .gallery-item {
            float: {$float};
            margin-top: 10px;
            text-align: center;
            width: {$itemwidth}%;
        }
        #{$selector} img {
            border: 2px solid #cfcfcf;
        }
        #{$selector} .gallery-caption {
            margin-left: 0;
        }
        /* see gallery_shortcode() in wp-includes/media.php */
    </style>\n\t\t";
}

$size_class = sanitize_html_class( $size );
$gallery_div = "<div id='$selector-sausage' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class} images'>";

/**
 * Filter the default gallery shortcode CSS styles.
 *
 * @since 2.5.0
 *
 * @param string $gallery_style Default gallery shortcode CSS styles.
 * @param string $gallery_div   Opening HTML div container for the gallery shortcode output.
 */
$output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );

$i = 0;
$first_image = reset($attachments);
$output .= '<a href="" itemprop="image" class="woocommerce-main-image zoom">';
$output .= wp_get_attachment_image( $first_image->ID, array(470,365), true, false );
$output .= '</a>';

$output .= '<div class="thumbnails">';

foreach ( $attachments as $id => $attachment ) {
    if ( ! empty( $link ) && 'file' === $link )
        $image_output = wp_get_attachment_link( $id, $size, false, false );
    elseif ( ! empty( $link ) && 'none' === $link )
        $image_output = wp_get_attachment_image( $id, $size, false );
    else
        $image_output = wp_get_attachment_link( $id, $size, true, false );

    $image_meta  = wp_get_attachment_metadata( $id );

    $orientation = '';
    if ( isset( $image_meta['height'], $image_meta['width'] ) )
        $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';

    $output .= $image_output;
}

if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
    $output .= "
        <br style='clear: both' />";
}

$output .= "
    </div>\n</div>\n";

return $output;
}
Author: Community, 2014-06-09

1 answers

Вы не передаете свой массив атрибутов методу shortcode_atts. Вы передаете неинициализированную переменную.

Ваша функция начинается с

function get_my_gallery_content ( $atts ) {

Но тогда вы больше не ссылаетесь на $atts. Код читает $attr, который является пустым.

Измените строку

), $attr, 'gallery'));

До

), $atts, 'gallery'));

Вам также необходимо изменить следующее, чтобы оно соответствовало имени переменной вашего аргумента:

if ( isset( $attr['orderby'] ) ) {
    $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
    if ( !$attr['orderby'] )
        unset( $attr['orderby'] );
}

Этот код читается $attr, но вы передаете $atts. Убедитесь, что они все совпадают.

Поскольку массив пуст, логика сводится только к извлечению дочерних элементов текущего сообщения. Вот почему вы видите их только в своих галереях.

 1
Author: Todd Rowan, 2014-06-13 06:11:41