You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何Hook WordPress的post_gallery函数修改图库样式及图片属性?

How to Customize WordPress Galleries: Add Classes to <dl> and ACF-Controlled Full-Screen Images

Got it, let's break down your two customization needs into actionable, code-backed steps—both are totally achievable with WordPress hooks and ACF. Here's how to make it happen:

1. Add Custom Class to Gallery <dl> Elements via post_gallery Hook

WordPress uses the post_gallery filter to generate gallery markup, so we can override the default output to inject your custom class into the <dl> tags wrapping each gallery item.

Add this code to your theme's functions.php file (or a custom plugin, which is safer for avoiding theme update conflicts):

add_filter( 'post_gallery', 'custom_gallery_dl_class', 10, 2 );
function custom_gallery_dl_class( $output, $attr ) {
    // Bail if no images are selected
    if ( empty( $attr['ids'] ) ) {
        return $output;
    }

    // Set default gallery attributes
    $attr = shortcode_atts( array(
        'order'      => 'ASC',
        'orderby'    => 'menu_order ID',
        'id'         => $post ? $post->ID : 0,
        'itemtag'    => 'dl',
        'icontag'    => 'dt',
        'captiontag' => 'dd',
        'columns'    => 3,
        'size'       => 'thumbnail',
        'include'    => '',
        'exclude'    => '',
        'link'       => ''
    ), $attr );

    $id = intval( $attr['id'] );

    // Fetch attachment IDs based on gallery settings
    if ( ! empty( $attr['include'] ) ) {
        $include = preg_replace( '/[^0-9,]+/', '', $attr['include'] );
        $_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $attr['order'], 'orderby' => $attr['orderby'] ) );
        
        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( ! empty( $attr['exclude'] ) ) {
        $exclude = preg_replace( '/[^0-9,]+/', '', $attr['exclude'] );
        $attachments = get_children( array( 'post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $attr['order'], 'orderby' => $attr['orderby'] ) );
    } else {
        $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $attr['order'], 'orderby' => $attr['orderby'] ) );
    }

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

    // Build custom gallery output
    $output = "<div class='gallery gallery-columns-{$attr['columns']}'>";

    foreach ( $attachments as $id => $attachment ) {
        $itemtag = tag_escape( $attr['itemtag'] );
        $icontag = tag_escape( $attr['icontag'] );
        $captiontag = tag_escape( $attr['captiontag'] );
        
        // Add your custom class here (rename 'custom-gallery-item' to whatever you need)
        $itemclass = "class='gallery-item custom-gallery-item'";

        $output .= "<{$itemtag} {$itemclass}>";
        $output .= "
            <{$icontag} class='gallery-icon'>";

        if ( ! empty( $attr['link'] ) && 'file' === $attr['link'] ) {
            $output .= wp_get_attachment_link( $id, $attr['size'], false, false );
        } elseif ( ! empty( $attr['link'] ) && 'none' === $attr['link'] ) {
            $output .= wp_get_attachment_image( $id, $attr['size'], false );
        } else {
            $output .= wp_get_attachment_link( $id, $attr['size'], true, false );
        }
        $output .= "</{$icontag}>";

        if ( $captiontag && trim( $attachment->post_excerpt ) ) {
            $output .= "
                <{$captiontag} class='wp-caption-text gallery-caption'>
                " . wptexturize( $attachment->post_excerpt ) . "
                </{$captiontag}>";
        }

        $output .= "</{$itemtag}>";
    }

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

    return $output;
}

The key change here is the $itemclass line—we added your custom class alongside WordPress's default gallery-item class on the <dl> tag.

2. ACF Toggle for Full-Screen Images + Use Large Size for Optimization

Next, let's set up the ACF switch to control full-screen images, then adjust the image source to use the Large size (for faster loading) for toggled attachments.

Step 1: Create the ACF Field

  1. Go to Custom Fields > Add New in your WordPress admin.
  2. Build a new Field Group with these settings:
    • Title: e.g., "Attachment Full-Screen Settings"
    • Location: Show this field group if Attachment is equal to All
    • Add a field:
      • Field Type: True/False
      • Field Name: enable_fullscreen_image (keep this exact name for the code to work)
      • Label: "Enable Full-Screen Image"
      • Default Value: No
  3. Publish the field group. You'll now see this toggle in every media attachment's edit screen.

Update the foreach loop in the custom_gallery_dl_class function above with this modified code. This checks the ACF toggle, swaps the image size to Large if enabled, and adds a custom class for styling:

foreach ( $attachments as $id => $attachment ) {
    // Check if full-screen is enabled via ACF
    $enable_fullscreen = get_field( 'enable_fullscreen_image', $id );
    
    // Use Large size if full-screen is enabled, else use gallery's default size
    $image_size = $enable_fullscreen ? 'large' : $attr['size'];
    $image_url = wp_get_attachment_image_url( $id, $image_size );
    $image_alt = get_post_meta( $id, '_wp_attachment_image_alt', true );

    $itemtag = tag_escape( $attr['itemtag'] );
    $icontag = tag_escape( $attr['icontag'] );
    $captiontag = tag_escape( $attr['captiontag'] );
    
    // Add your custom dl class here
    $itemclass = "class='gallery-item custom-gallery-item'";

    $output .= "<{$itemtag} {$itemclass}>";
    $output .= "
        <{$icontag} class='gallery-icon'>";

    if ( ! empty( $attr['link'] ) && 'file' === $attr['link'] ) {
        // Link to full-size file but display Large size for optimization
        $link_url = wp_get_attachment_url( $id );
        $output .= "<a href='{$link_url}' class='{$enable_fullscreen ? 'fullscreen-link' : ''}'><img src='{$image_url}' alt='{$image_alt}' class='{$enable_fullscreen ? 'fullscreen-image' : ''}' /></a>";
    } elseif ( ! empty( $attr['link'] ) && 'none' === $attr['link'] ) {
        $output .= "<img src='{$image_url}' alt='{$image_alt}' class='{$enable_fullscreen ? 'fullscreen-image' : ''}' />";
    } else {
        // Link to attachment page
        $attachment_page_url = get_permalink( $id );
        $output .= "<a href='{$attachment_page_url}' class='{$enable_fullscreen ? 'fullscreen-link' : ''}'><img src='{$image_url}' alt='{$image_alt}' class='{$enable_fullscreen ? 'fullscreen-image' : ''}' /></a>";
    }
    $output .= "</{$icontag}>";

    if ( $captiontag && trim( $attachment->post_excerpt ) ) {
        $output .= "
            <{$captiontag} class='wp-caption-text gallery-caption'>
            " . wptexturize( $attachment->post_excerpt ) . "
            </{$captiontag}>";
    }

    $output .= "</{$itemtag}>";
}

What this does:

  • Checks the ACF toggle for each attachment
  • Swaps the image source to the Large size (instead of full size) when full-screen is enabled, cutting down on page load time
  • Adds fullscreen-image to the <img> tag and fullscreen-link to the wrapping <a> tag—use these classes to add CSS/JS for full-screen behavior (like a lightbox or zoom effect)

Quick Notes

  • Verify your WordPress Settings > Media has a "Large" image size defined (adjust dimensions if needed)
  • If you prefer a custom image size over Large, replace 'large' with your custom size name
  • For the actual full-screen functionality, add CSS (e.g., cursor: zoom-in) or integrate a lightbox plugin that targets the fullscreen-image class

内容的提问来源于stack exchange,提问作者Gas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:58:04