Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Dynamically Add a Custom Class to Image Links in WordPress

WordPress has made huge improvements to the Media Library over time but one thing that has been lacking is the ability to add custom classes to image links as an option. Adding a Class to an image link has many benefits, including but not limited to CSS styling or opening images inside of lightboxes or galleries. In this tutorial we will teach you how to Dynamically Add a Custom Class to image links in WordPress by utilizing PHP functions.

Dynamically Add a Custom Class to Image Links via a WordPress Function

In order to dynamically add a class to image links in WordPress, we will need to add a PHP filter to the WordPress functions file. Open your functions.php file then copy and paste the code below. Make sure that you change where it says ‘YOUR-CLASS-HERE’ to whatever you want to name your custom class. Now, any new images with links inserted into a WordPress post via the Media Library will automatically have the custom class added to it.

PHP

function add_class_to_image_links($html, $attachment_id, $attachment) {
    $linkptrn = "/]*>/";
    $found = preg_match($linkptrn, $html, $a_elem);
    // If no link, do nothing
    if($found 

Troubleshooting

If you are having problems getting this tutorial to work please reread the tutorial and try again, if you still cannot get it to work please leave us a comment below and we will respond as soon as possible. Please do not email us with problems regarding this tutorial, only comments will be responded to.



This post first appeared on Blog | Daddy Design, please read the originial post: here

Share the post

How to Dynamically Add a Custom Class to Image Links in WordPress

×

Subscribe to Blog | Daddy Design

Get updates delivered right to your inbox!

Thank you for your subscription

×