Cambiar la salida predeterminada de la galería de Wordpress


Estoy buscando utilizar el Wordpress galería atajo pero quiero atar la salida en el Foundation Orbit plugin (para hacer un control deslizante). Este es el HTML que estoy buscando para la salida:

<div class="slideshow-wrapper">
    <div class="preloader"></div>
    <ul data-orbit>
        <li>
            <img src="img1.png" alt="bla bla bla" />
        </li>
        <li>
            <img src="img2.png" alt="bla bla bla" />
        </li>
        <li>
            <img src="img3.png" alt="bla bla bla" />
        </li>
        <li>
            <img src="img4.png" alt="bla bla bla" />
        </li>
    </ul>
</div>

Es posible poner algo en functions.php (o similar) para lograr esto?

Author: Sheixt, 2013-11-06

4 answers

Sí, de hecho. Hace bastante tiempo he encontrado este código y lo he estado usando desde entonces. Es genial personalizar la galería predeterminada de WP a lo que quieras.

Hay un filtro para post_gallery que puede usar para personalizar todas las galerías WP predeterminadas. Aquí hay una muestra del código que uso adaptado a la plantilla que proporcionaste. Lo he aclarado todo lo posible.

La primera parte de la función es más o menos el manejo de archivos adjuntos de la galería, por lo que probablemente solo querrá cambia la segunda mitad, la que determina la salida de tu plantilla de galería (sigue los comentarios):

add_filter('post_gallery', 'my_post_gallery', 10, 2);
function my_post_gallery($output, $attr) {
    global $post;

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

    extract(shortcode_atts(array(
        'order' => 'ASC',
        'orderby' => 'menu_order ID',
        'id' => $post->ID,
        'itemtag' => 'dl',
        'icontag' => 'dt',
        'captiontag' => 'dd',
        'columns' => 3,
        'size' => 'thumbnail',
        'include' => '',
        'exclude' => ''
    ), $attr));

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

    if (!empty($include)) {
        $include = preg_replace('/[^0-9,]+/', '', $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];
        }
    }

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

    // Here's your actual output, you may customize it to your need
    $output = "<div class=\"slideshow-wrapper\">\n";
    $output .= "<div class=\"preloader\"></div>\n";
    $output .= "<ul data-orbit>\n";

    // Now you loop through each attachment
    foreach ($attachments as $id => $attachment) {
        // Fetch the thumbnail (or full image, it's up to you)
//      $img = wp_get_attachment_image_src($id, 'medium');
//      $img = wp_get_attachment_image_src($id, 'my-custom-image-size');
        $img = wp_get_attachment_image_src($id, 'full');

        $output .= "<li>\n";
        $output .= "<img src=\"{$img[0]}\" width=\"{$img[1]}\" height=\"{$img[2]}\" alt=\"\" />\n";
        $output .= "</li>\n";
    }

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

    return $output;
}

Simplemente pégalo en tu archivo functions.php y modifícalo para adaptarlo a tus necesidades. Estoy bastante seguro de que va a funcionar para usted, ya que han trabajado para mí :)

 73
Author: mathielo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-06 04:54:47

Súper respuesta Mathielo.

Sin embargo, necesitaba la opción de incluir un título, así que he modificado su código para usar la función wp_prepare_attachment_for_js() ya que parece proporcionar los datos necesarios.

add_filter('post_gallery', 'my_post_gallery', 10, 2);
function my_post_gallery($output, $attr) {
global $post;

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

extract(shortcode_atts(array(
    'order' => 'ASC',
    'orderby' => 'menu_order ID',
    'id' => $post->ID,
    'itemtag' => 'dl',
    'icontag' => 'dt',
    'captiontag' => 'dd',
    'columns' => 3,
    'size' => 'thumbnail',
    'include' => '',
    'exclude' => ''
), $attr));

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

if (!empty($include)) {
    $include = preg_replace('/[^0-9,]+/', '', $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];
    }
}

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

// Here's your actual output, you may customize it to your need
$output = "<div class=\"slideshow-wrapper\">\n";
$output .= "<div class=\"preloader\"></div>\n";
$output .= "<ul data-orbit>\n";

// Now you loop through each attachment
foreach ($attachments as $id => $attachment) {
    // Fetch all data related to attachment 
    $img = wp_prepare_attachment_for_js($id);

    // If you want a different size change 'large' to eg. 'medium'
    $url = $img['sizes']['large']['url'];
    $height = $img['sizes']['large']['height'];
    $width = $img['sizes']['large']['width'];
    $alt = $img['alt'];

    // Store the caption
    $caption = $img['caption'];

    $output .= "<li>\n";
    $output .= "<img src=\"{$url}\" width=\"{$width}\" height=\"{$height}\" alt=\"{$alt}\" />\n";

    // Output the caption if it exists
    if ($caption) { 
        $output .= "<div class=\"orbit-caption\">{$caption}</div>\n";
    }
    $output .= "</li>\n";
}

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

return $output;
}
 20
Author: StandardSpace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-26 12:14:12

Sé que la pregunta original ha sido respondida, pero solo quería compartir lo que he hecho con el fragmento de filtro en caso de que ayude a alguien más. He habilitado el plugin jquery 'Justified Gallery' de Miro Mannino http://miromannino.com/projects/justified-gallery / para trabajar con galerías de Wordpress en Wordpress 3.9 ... Aquí está el código con los cambios que hice para que funcione... (img size light thumb es mi miniatura personalizada para preservar las dimensiones de la imagen pero mantener los tiempos de carga de la página abajo.)

// Custom Gallery

add_filter( 'post_gallery', 'my_post_gallery', 10, 2 );
function my_post_gallery( $output, $attr) {
global $post, $wp_locale;

static $instance = 0;
$instance++;

// 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'] );
}

extract(shortcode_atts(array(
    'order'      => 'ASC',
    'orderby'    => 'menu_order ID',
    'id'         => $post->ID,
    'itemtag'    => 'dl',
    'icontag'    => 'dt',
    'captiontag' => 'dd',
    'columns'    => 3,
    'size'       => 'light-thumb',
    'include'    => '',
    'exclude'    => ''
), $attr));

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

if ( !empty($include) ) {
    $include = preg_replace( '/[^0-9,]+/', '', $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) ) {
    $exclude = preg_replace( '/[^0-9,]+/', '', $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);
$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';

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

$output = apply_filters('gallery_style', "
    <style type='text/css'>
        #{$selector} {
            margin: auto;
        }
        #{$selector} .gallery-item {
            float: {$float};
            margin-top: 0px;
            text-align: center;
            width: {$itemwidth}%;           }
        #{$selector} img {
            border: 0;
        }
        #{$selector} .gallery-caption {
            margin-left: 0;
        }
    </style>
    <!-- see gallery_shortcode() in wp-includes/media.php -->


    <div id='$selector' class='gallery galleryid-{$id}'>");
    $output = "<div id=\"mygallery\">\n";




$i = 0;
foreach ( $attachments as $id => $attachment ) {
    $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);


    $output .= "<{$itemtag} class='gallery-item'>";
    $output .= "
        <{$icontag} class='gallery-icon'>
            $link
        </{$icontag}>";
    if ( $captiontag && trim($attachment->post_excerpt) ) {
        $output .= "
            <{$captiontag} class='gallery-caption'>
            " . wptexturize($attachment->post_excerpt) . "
            </{$captiontag}>";
    }
    $output .= "</{$itemtag}>";
    if ( $columns > 0 && ++$i % $columns == 0 )
        $output .= '<br style="clear: both" />';
}

$output .= "
    <br style='clear: both;' />
    </div>\n";


return $output;

}

Funciona como una delicia. Gracias por compartir el filtro - era justo lo que estaba buscando.

 3
Author: Stephanie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-30 11:03:12

Así que si desea generar otra cadena como img title o img desc, simplemente use esta construcción

$title =im img ['title'];

Este es el comentario para Super respuesta Mathielo (segunda respuesta), y esta solución universal, no solo la fundación zubr

 1
Author: AlexanderShustik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-04 08:51:35