如何在锚标记内添加“data-caption”

时间:2014-07-13 作者:Accore LTD

下面是自定义库代码。

function custom_gallery_shortcode( $attr = array(), $content = \'\' )

{

        $attr[\'itemtag\']        = "li";
        $attr[\'icontag\']        = "";
        $attr[\'captiontag\']     = "p";

        // Run the native gallery shortcode callback:    
        $html = gallery_shortcode( $attr );
        // Remove all tags except a, img,li, p
        $html = strip_tags( $html, \'<a><img><li><p>\' );
        // Some trivial replacements:
        $from = array(  

            "class=\'gallery-item\'", 
            "class=\'gallery-icon landscape\'", 
            \'class="attachment-thumbnail"\',
            \'a href=\', 

        );              

        $to = array( 

            \'\',

            \'\',

            \'\', 

            \'a data-caption="" class="ilightbox" href=\', 

        );

        $html = str_replace( $from, $to, $html );

        // Remove width/height attributes:

        $html = preg_replace( \'/(width|height)=\\"\\d*\\"\\s/\', "", $html );
        // Wrap the output in ul tags:

        $html = sprintf( \'<ul class="gallery">%s</ul>\', $html );

        return $html;

}



add_shortcode( \'gallery\', \'custom_gallery_shortcode\' );
add_filter( \'use_default_gallery_style\', \'__return_false\' );
但现在我想在a中添加图像标题。看看我的代码\'a data-caption="" class="ilightbox" href=\', there data caption=“image caption i want to add”现在图像标题出现在

像这样

  • <a data-caption="" class="ilightbox" href="http://xxxxxxx.com/Snack-bar-1024x682.jpg"><img src="http:xxxxxxxxxx.com/Snack-bar-1024x682-150x150.jpg" alt="testing caption"></a>
    
                    <p class="wp-caption-text gallery-caption">
                    testing caption
                    </p></li>
    

  • 1 个回复
    最合适的回答,由SO网友:Domain 整理而成

    您可以尝试以下代码在html代码中添加新属性:

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    
    foreach ($dom->getElementsByTagName(\'a\') as $item) {
    
        $item->setAttribute(\'data-caption\', \'This is an anchor tag\');
        echo $dom->saveHTML();
        exit;
    }
    

    结束

    相关推荐

    Split Content and Gallery

    有没有办法将帖子内容和库短代码分开。我想在我的正常内容之外显示库,无论其放置方式或位置如何。我可以用它来获取短代码本身:if(has_shortcode(get_the_content(), \'gallery\')){ $pattern = get_shortcode_regex(); preg_match(\"/$pattern/s\", get_the_content(), $matches); echo do_shortcode($matches[