Adding HTML Tags and Classes within Link Tags for Wordpress Posts

How can I add classes and an HTML tag inside a link tag of a Post in WordPress? Currently, when I link a word to one of my WordPress pages it looks like this:

<a href="http://localhost/website/contact/">contact</a>

I would like the linked word to appear as follows:

<a href="http://localhost/website/contact/" class="class1 class2"><span>contact</span></a>

This is because my theme uses span for a hover feature.

If possible, I want this modification to apply only to the Post (Blog) section, using a class that all posts share: post-contents.

While I know I can manually edit the HTML code of each post, I prefer a universal solution where every time I add a link in a post, the appropriate classes and span tags are automatically included. Any suggestions?

Answer №1

This method should prove effective:

function modify_anchor_tags_with_span( $content ) {
        if ( ! is_admin() && preg_match( '~<a(.*?)>(.*?)</a>~', $content ) ) {
            $content = preg_replace_callback( '~<a(.*?)>(.*?)</a>~', '_add_span_to_anchor', $content );
    }
    return $content;
}
add_filter('the_content', 'modify_anchor_tags_with_span', 10);

function _add_span_to_anchor( $matches ) {
    if ( ! ( $title = strip_tags( $matches[2] ) ) ) { // If there is only an image inside the anchor
        return '<a' . $matches[1] . '>' . $matches[2] . '</a>';
    } else {
        return '<a' . $matches[1] . '><span data-title="' . esc_attr( $title ) . '">' . $matches[2] . '</span></a>';
    }
}

The purpose of this function is to attach to the the_content filter and insert a span within all anchor tags.

Please note that if the anchor contains an image, a span will not be inserted. As mentioned in another response from a different post by Nikola Ivanov Nikolov

Afterwards, implement a filter to manage the anchors...

add_filter('the_content', 'addClassToLinks');
function addClassToLinks($content){
    return str_replace('<a ', "<a class='myclass'", $content);
}

I hope this solution proves useful for you.

Best regards, -B.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking to incorporate HTML5 into my Python script in order to play a video from a website using a link

Currently, I have a Python script that utilizes the WSGI module in Apache. The table consists of an ID and video_filename column. The video_filename column contains a single filename in each row, where each filename is specifically for a video with the .m ...

h1 text obscured by video backdrop

Having trouble with a h1 tag appearing behind my video element. I'm fairly new to programming so please excuse any ignorance on my part. I attempted to overlay a header on top of a video, but it was unsuccessful. I've also experimented with z-in ...

Use a personalized CSS class with the Kendo Dropdown Widget

Is there a way to assign a custom CSS class to the dropdown HTML container that is created when using the .kendoDropDownList() method on a <select> or <input> element? In this fiddle ( http://jsfiddle.net/lav911/n9V4N/ ) you can see the releva ...

What steps can be taken to obtain the fully computed HTML rather than the source HTML?

Is there a way to access the final computed HTML of a webpage that heavily relies on javascript to generate its content, rather than just the source HTML? For example, if a page contains script functions that dynamically generate HTML, viewing the page sou ...

What are the best techniques for styling the aria label element in HTML?

Looking to enhance the appearance of a button label upon hover. Curious about how I can customize the aria-label element to resemble the design in the screenshot provided below. https://i.sstatic.net/Mjr7q.png ...

How can I ensure that Chakra UI MenuList items are always visible on the screen?

Currently, I am utilizing Chakra UI to design a menu and here is what I have so far: <Menu> <MenuButton>hover over this</MenuButton> <MenuList> <Flex>To show/hide this</Flex> </MenuList> </ ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

The function "getElementsByClassName" in Javascript is malfunctioning

I have redesigned my website by implementing an interactive feature where users can click on a tree image to remove it and replace it with a number using JavaScript. Initially, I targeted the specific tree with the following code: document.getElementById( ...

The color of the form button should switch when the user hovers over it with their mouse pointer

Here is my form with a custom button: <form action="login_form.php" method="POST" id="login_form"> Email <input name="email" type="text" size="25" placeholder="type your email"/> Password <input name="password" type="text" size ...

Tips for aligning a row at the bottom within a nested column

Desired Outcome I am struggling to arrange two smaller images next to a larger image using Bootstrap 4. Specifically, I am having difficulty aligning one of the smaller images at the bottom so that it matches the alignment of the larger image. The layout ...

Transform collapsible color upon materialize click

Is there a way to change the color of the collapsible header only when clicked? I'm struggling with adding the color inside the class element while calling the "connect" function. Can this be achieved? <div class="collapsible-header" onclick="conn ...

Utilize the get method to showcase data in a material UI table for a React application

Just starting out with React. Managed to create a table component with hard-coded data. However, I now have all the data stored in table.json. Can someone guide me on how to fetch values from table.json using an axios get request an ...

The Angular JS routes are not properly loading the required file from the provided TemplateURL when receiving a response from Node

I am trying to retrieve data from a MySQL database using node (routes.js) and have the results injected into club.html, which is then dynamically updated in index.html using ng-view. However, it seems that the JSON response from node is displaying directly ...

Using HTML and CSS to create a Contact Form

Greetings! I have come across this contact form code: /* Custom Contact Form Styling */ input[type=text], [type=email], select, textarea { width: 100%; padding: 12px; border: 1px solid #555; margin-top: 6px; margin-bottom: 16px; resize: v ...

Scroll dynamically to a div upon clicking and looping through its content

When the user clicks on the first paragraph with the class "targetgo", I want the page to scroll to the element with the class "size1". The same goes for the second paragraph with the class "size2" and so on. As I will have more than 25 similar instances ...

Changing the value of a form input name after a $scope.$watch event is activated

In my AngularJS 1.4 project, I have a form input element where I am attempting to dynamically set the name attribute. <input type="email" name="{{ctrl.name}}" class="form-control" id="email" ng-minlength="5" required> The assignment of the name att ...

Encountering an issue with the router that is unable to correctly read the head.html and tail

As a student diving into Express, I have come across a slight issue that I need help with. Within my routes/index.js file, the following code block exists: router.post('/orders.html', function(req, res, next) { var fhead = __dirname+ "/ ...

What is the method for verifying a condition within a Javascript function?

Recently delving into Javascript, I have encountered a situation with a JS method. It seems that most of the time, both the SSID and SecurityMode are the same in the lists of wifi networks I receive. I would like to filter out instances where both SSID and ...

Informing users of the availability of an iOS app on the website

Is there a simple way to notify iOS users about your app when they visit your website? While I know how to detect user agents and write JavaScript, I'm curious if there is an existing library for this purpose. In the absence of such a solution, are t ...

Exploring the use of the map function for iterating in a stepper component of

I've been attempting to integrate Redux Form into my stepper component. However, I'm facing an issue where adding form fields results in them being displayed in all three sections. To address this, I started reviewing the code for the stepper. I ...