Last active
June 1, 2018 00:30
-
-
Save luistinygod/4105892313328cdf67ad459c87b434c5 to your computer and use it in GitHub Desktop.
WordPress: Manage featured posts using WordPress menus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the featured posts for a specific menu location | |
* | |
* @param string $theme_location As defined in the register_nav_menus call | |
* | |
* @return array|bool|mixed Array of Post IDs | |
*/ | |
function my_theme_get_featured_posts( $theme_location = '' ) { | |
$last_changed = wp_cache_get_last_changed( 'my_group_menus' ); | |
$cache_key = 'menu_'. md5( $theme_location ) . $last_changed; | |
if ( false === ( $featured = wp_cache_get( $cache_key, 'my_theme' ) ) ) { | |
$locations = get_nav_menu_locations(); | |
if( empty( $theme_location ) || !isset( $locations[ $theme_location ] ) ) { | |
return array(); | |
} | |
$menu = get_term( $locations[ $theme_location ], 'nav_menu' ); | |
if( empty( $menu->term_id ) ) { | |
return array(); | |
} | |
$menu_items = wp_get_nav_menu_items( $menu->term_id ); | |
if( empty( $menu_items ) || !is_array( $menu_items ) ) { | |
return array(); | |
} | |
$featured = array(); | |
foreach( $menu_items as $item ) { | |
// here I'm filtering to only get post objects | |
if( $item->type != 'post_type' ) { | |
continue; | |
} | |
$featured[] = $item->object_id; | |
} | |
wp_cache_set( $cache_key, $featured, 'my_theme', DAY_IN_SECONDS ); | |
} | |
return $featured; | |
} | |
/** | |
* Hook on wp_update_nav_menu to burn a new 'last_changed' timestamp | |
*/ | |
function my_theme_update_menu() { | |
wp_cache_set( 'last_changed', microtime(), 'my_group_menus' ); | |
} | |
add_action( 'wp_update_nav_menu', 'my_theme_update_menu' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* On a WordPress template, get the featured posts for the slider | |
*/ | |
$featured = my_theme_get_featured_posts( 'slider' ); | |
global $post; | |
?> | |
<section class="hero"> | |
<?php if( !empty( $featured ) && is_array( $featured ) ): ?> | |
<div class="hero-slider"> | |
<?php | |
foreach( $featured as $slide ) : | |
$post = get_post( $slide ); | |
setup_postdata( $post ); | |
get_template_part( 'parts/slide-hero', get_post_type() ); | |
endforeach; wp_reset_postdata(); ?> | |
</div> | |
<?php endif; ?> | |
</section> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read more about this gist on my blog.