John Davidson

php - Change link of Wordpress menu item for posts

0 comments
Message:


I have a menu that is used throughout the entire site (pages and posts). I would like to change the link of one single menu item (custom link) if the menu is displayed on on a blog post.
I tried using the plugin Conditional Menus which could do the job, but has the disadvantage that I would need to recreate the entire menu for each language and repeat this everytime the menu is updated.


I think it would be smarter to do this through php. I found this to check post vs. page:


<?php

if(get_post_type() === 'post') {
// Do something
}

?>

Would it be possible to set the href of the <a> tag in menu-item-123 within this if-statement? Also, is there a way I can add this to functions.php in the child theme or does it need to placed somewhere else? Thanks!



My Answer:
Yes, it is possible to change the link of a menu item based on whether it is displayed on a blog post using PHP. You can add the following code to your child theme's functions.php file:

php
function change_menu_link_for_posts($items, $args) {
if (is_single() && $args->theme_location == 'your_menu_location') {
foreach ($items as $item) {
if ($item->ID == 123) { // Change 123 to the ID of the menu item you want to modify
$item->url = 'new-url-here'; // Change 'new-url-here' to the new URL you want to set
}
}
}
return $items;
}
add_filter('wp_nav_menu_objects', 'change_menu_link_for_posts', 10, 2);


Replace 'your_menu_location' with the actual theme location of your menu. Also, replace 123 with the ID of the menu item you want to modify and 'new-url-here' with the new URL you want to set for that menu item.

This code will check if the current page is a single blog post and if the menu being displayed is the specified menu location. If both conditions are met, it will change the URL of the specified menu item.

Make sure to test this code thoroughly on your site to ensure it works as expected.

Rate this post

5 of 5 based on 8984 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us