How do I have the correct category show up on my post page?
-
Quick example:
I have the categories:
Everything
Small
Animal
I have a post:
Snail, which is assigned to all of those categories.
When I go to my category page Small, and click on the post Snail, I would like the resulting page to show
Small: Snail
When I go to my category page Animal and click on the post Snail, I would like the resulting page to show
Animal: Snail -
Hi @krisskrangle,
I understand that you need to dynamically change the post title on the single post page based on the category from which the user navigated.
This involves using JavaScript and storing the category in a session or local storage. Here’s a step-by-step guide to accomplish this:
Step 1: Add JavaScript to Store CategoryFirst, you need to add JavaScript code to store the category name in local storage when a user clicks on a post link.
- Add JavaScript to Your Theme:
- Go to
Appearance > Theme Editor. - Select your theme’s
header.phpfile. - Add the following script before the closing
</head>tag:
- Go to
<script> document.addEventListener('DOMContentLoaded', function() { var postLinks = document.querySelectorAll('.category a'); postLinks.forEach(function(link) { link.addEventListener('click', function() { var category = link.closest('.category').querySelector('h1').textContent; localStorage.setItem('categoryName', category); }); }); }); </script>Adjust the selector to match your theme’s structure if necessary.
Step 2: Modify the Post Title
Next, you need to modify the post title on the single post page based on the stored category name.
- Add PHP Code to Your Theme:
- Go to
Appearance > Theme Editor. - Select your theme’s
functions.phpfile. - Add the following code:
- Go to
function modify_post_title($title) { if (is_single() && in_the_loop() && !is_admin()) { ?> <script> document.addEventListener('DOMContentLoaded', function() { var categoryName = localStorage.getItem('categoryName'); if (categoryName) { var postTitle = document.querySelector('h1.entry-title'); postTitle.textContent = categoryName + ': ' + postTitle.textContent; } }); </script> <?php } return $title; } add_filter('the_title', 'modify_post_title');This should dynamically update the post title on the single post page based on the category from which the user navigated. If you need further customization, feel free to ask!
- Add JavaScript to Your Theme:
- The topic ‘How do I have the correct category show up on my post page?’ is closed to new replies.