Skip to content

Instantly share code, notes, and snippets.

@rmpel
Created January 12, 2023 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmpel/1c764d2a009859cda443c5e7b1040ef7 to your computer and use it in GitHub Desktop.
Save rmpel/1c764d2a009859cda443c5e7b1040ef7 to your computer and use it in GitHub Desktop.
WordPress + Widget Context -> For use with a widget with a menu, to show the widget only on pages in that menu.
<?php
add_filter( 'widget_contexts', function ( $contexts ) {
$contexts['menu_content'] = [
'label' => 'Menu-widget content',
'description' => 'Show only on pages that have its url/page/post listed in a menu',
'weight' => 11,
];
return $contexts;
}, 10, 2 );
add_filter( 'widget_context_control-menu_content', function ( $control_args ) {
$wc = WidgetContext::instance();
$menus = wp_get_nav_menus();
$out = [];
$out[] = '<style>.context-group-menu_content .context-group-wrap { max-height:10em; overflow:auto; padding:0.5em; margin-bottom:0.5em; background:#fff; border:1px solid #ddd; }
.context-group-menu_content label { display:block; padding:0.25em 0; }
</style>';
foreach($menus as $menu) {
$out[] = $wc->make_simple_checkbox( $control_args, 'menu-widget-filter-enabled-' . $menu->term_id, $menu->name );
}
return implode('', $out);
} );
add_filter( 'widget_context_check-menu_content', function ( $allowed, $options ) {
global $post;
$post_id = (int) $post->ID;
$post_url = get_permalink( $post_id );
$post_url_path = wp_parse_url( $post_url, PHP_URL_PATH );
if ( ! $post || ! $post instanceof WP_Post || ! $post->ID ) {
return $allowed;
}
foreach ( $options as $option_name => $option_value ) {
if ( ! $option_value ) {
continue;
}
preg_match( '/menu-widget-filter-enabled-(\d+)/', $option_name, $m );
if ( ! $m ) {
continue;
}
$menu_id = $m[1] ?? false;
if ( ! $menu_id ) {
continue;
}
$items = wp_get_nav_menu_items( $menu_id );
foreach ( $items as $item ) {
// pages and posts
if ( ( $post->post_type === $item->object || 'page' === $item->object ) && (int) $item->object_id === $post_id ) {
return true;
}
// custom links
if ( 'custom' === $item->object ) {
$custom_link_path = wp_parse_url( $item->url, PHP_URL_PATH );
if ( $post_url_path === $custom_link_path ) {
return true;
}
}
}
}
return $allowed;
}, 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment