Home > other >  How to add PHP code to only a certain page in wordpress
How to add PHP code to only a certain page in wordpress

Time:02-23

I have added styling to my anchor tag and have made the text-decoration to none to the entire website. But I want the blog section of my website to underline the links.

I'm using the code snippet plugin in wordpress as I don't have direct access to the files.

And this is the code that I'm using.

add_action( 'wp_head', function  () { ?>
    <style>
        
         a:link {
            text-decoration: underline;
        }
</style>
<?php } );

The problem is that this PHP code gets applied to my entire website which is not what I want. I only want this to be applied to the body section of the blog content.

I would love to have someone assist me with this problem.

Thank you.

CodePudding user response:

This is a job for CSS (inside a <style> tag) with specific selectors. Your CSS selector, a:link is very non-specific. That is, the browser uses it whenever it sees an anchor <a> tag.

You need the browser to use it only on some anchor tags. So, you use a more specific selector.

Try using this CSS to style the links within articles in your posts and pages.

div.site-content main article a:link {
    text-decoration: underline;
}

It affects anchor tags only in html nested inside a hierarchy of HTML elements. Most themes use these elements.

If you want to style just posts (not pages), put article.post in the selector instead.

div.site-content main article.post a:link {
    text-decoration: underline;
}

You can add CSS to your site without the Code Snippets plugin, and without php code. Go to Appearance -> Customize. At the bottom of the left column choose Additional CSS. Then put in the CSS you need.

If you want to be able to figure this out for yourself, right-click in the browser element you want to style and choose Inspect. You'll see the HTML for that element along with the elements it's nested inside.

Additional CSS is a good setup because it survives plugin updates, and because you don't neet to hack any php to get it to work.

  • Related