未定义的偏移量:显示 the_content() 时出现 -1 错误;在创世纪儿童主题中

问题描述

我使用此代码在每个页面标题之后显示来自自定义帖子类型的帖子的内容

$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;

它适用于主页,但在所有其他页面上我收到此错误

Notice: Undefined offset: -1 in /wp-includes/post-template.PHP on line 325

我使用 Genesis 框架。

在这里做错了什么?

解决方法

自己找到了答案。

我将该函数添加到“genesis_after_header”钩子中,这是一个模板文件钩子。相反,查询和相关函数应该存在于该钩子之外。我使用输出缓冲将 the_content() 放入一个变量中,并将其放入挂钩函数中。请参阅下面的代码,了解我的最终运行代码。

$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();