Skip to content

Instantly share code, notes, and snippets.

@damiencarbery
Last active January 6, 2020 22:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save damiencarbery/b430bb6b14e1183c2a120f7450461a61 to your computer and use it in GitHub Desktop.
Save damiencarbery/b430bb6b14e1183c2a120f7450461a61 to your computer and use it in GitHub Desktop.
Shortcode in a menu - it's possible to use a shortcode as a menu url but it's not trivial - https://www.damiencarbery.com/2019/11/shortcode-in-a-menu/
<?php
/*
Plugin Name: Shortcode in menu - Convert to dynamic url
Plugin URI: https://www.damiencarbery.com
Description: Change a shortcode in menu url to a dynamic url. Advanced WordPress group question: https://www.facebook.com/groups/advancedwp/permalink/2734099893318874/
Author: Damien Carbery
Version: 0.1
*/
add_filter( 'nav_menu_link_attributes', 'dcwd_nav_menu_link_attributes', 10, 4 );
function dcwd_nav_menu_link_attributes( $atts, $item, $args, $depth ) {
//error_log( "Atts: " . var_export( $atts, true ) );
//error_log( "Item: " . var_export( $item, true ) );
//error_log( "Depth: " . var_export( $depth, true ) );
// If MENU_SHORTCODE is found then change it.
// TODO: Allow for extra to be in href element and parse it.
if ( false !== strpos( $atts[ 'href' ], '[MENU_SHORTCODE]' ) ) {
// Simply overwrite the url with a set value
$atts[ 'href' ] = 'http://www.example.com';
// or use do_shortcode() - this requires an add_shortcode() function.
// Remove the 'http://' from the start and expand the shortcode
//$atts[ 'href' ] = substr( $atts[ 'href' ], strlen( 'http://' ) );
//$atts[ 'href' ] = do_shortcode( $atts[ 'href' ] );
}
return $atts;
}
<?php
/*
Plugin Name: Shortcode in menu - use do_shortcode()
Plugin URI: https://www.damiencarbery.com
Description: Use do_shortcode() to expand a shortcode in a menu.
Author: Damien Carbery
Version: 0.1
*/
add_filter( 'wp_nav_menu', 'do_shortcode' );
add_shortcode( 'MENU_SHORTCODE', 'dcwd_menu_shortcode_shortcode' );
function dcwd_menu_shortcode_shortcode( $atts, $content = "" ) {
return 'https://www.example.com';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment