Wordpress useful functions

1 全局添加图像链接参数 有时候调用Lightbox插件,需要在图片链接上加某些参数,已发布的文章也是,用以下代码添加data-lightbox=“lightbox”(或其他需要的参数) 来实现。 /** *Lightbox to image link globally */ add_filter('the_content', 'dukeyin_addlightbox'); function dukeyin_addlightbox($content) { global $post; $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i"; $replacement = '<a$1href=$2$3.$4$5 data-lightbox="lightbox" title="'.$post->post_title.'"$6>'; $content = preg_replace($pattern, $replacement, $content); return $content; } 另一种方式,修改单张图片,也修改相册的链接 <?php /** * Add data attributes for Fancybox */ // Gallery images function ccd_fancybox_gallery_attribute( $content, $id ) { // Restore title attribute $title = get_the_title( $id ); return str_replace('<a', '<a data-type="image" data-fancybox="gallery" title="' . esc_attr( $title ) . '" ', $content); } add_filter( 'wp_get_attachment_link', 'ccd_fancybox_gallery_attribute', 10, 4 ); // Single images function ccd_fancybox_image_attribute( $content ) { global $post; $pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i"; $replace = '<a$1href=$2$3.$4$5 data-type="image" data-fancybox="image">'; $content = preg_replace( $pattern, $replace, $content ); return $content; } add_filter( 'the_content', 'ccd_fancybox_image_attribute' ); ?>   ...

2018-08-14 · 4 min · Duke Yin