I use this code to show the content from a post from a custom post type after the header on each page.
$args = [
'numberposts' => 1,
'post_type' => 'theme_elements',
'meta_key' => 'location',
'meta_value' => 'mega-menu'
];
$mega_menu_content = new WP_Query( $args );
if ( $mega_menu_content->have_posts() ):
while ( $mega_menu_content->have_posts() ) : $mega_menu_content->the_post();
add_action( 'genesis_after_header', 'dex_add_mega_menu');
function dex_add_mega_menu() { ?>
<div class="dex-mega-menu dex-hidden">
<div class="dex-wrap">
<?php the_content(); ?>
</div>
</div>
<?php }
endwhile;
wp_reset_query();
endif;
It works on the home page, but on all other pages I get this error:
Notice: Undefined offset: -1 in /wp-includes/post-template.php on line 325
I use the Genesis Framework.
What am I doing wrong here?
Found the answer myself.
I was adding the function to the 'genesis_after_header' hook, which is a template file hook. Instead, the query and relative functions should live outside that hook. I used output buffering to get the_content() into a variable and put that in the hooked function instead. See code below for my final, functioning code.
$args = [
'numberposts' => 1,
'post_type' => 'theme_parts',
'meta_query' => [
[
'key' => 'location',
'value' => 'mega-menu'
]
]
];
$mega_menu_post_query = new WP_Query( $args );
if ( $mega_menu_post_query->have_posts() ):
while ( $mega_menu_post_query->have_posts() ) : $mega_menu_post_query->the_post();
ob_start();
the_content();
$content = ob_get_clean();
endwhile;
add_action( 'genesis_after_header', 'dex_add_mega_menu');
function dex_add_mega_menu() {
global $content;
?>
<div class="dex-mega-menu dex-hidden">
<div class="dex-wrap">
<?php echo $content ?>
</div>
</div>
<?php }
endif;
wp_reset_query();