Wordpress single.php的另一个get_post函数可以破坏第一个函数

时间:2018-12-31 15:50:49

标签: php wordpress custom-wordpress-pages

我正在尝试处理两个get_post函数,在single.php中,第一个get_post函数是来自wordpress的帖子,但是之后,我将get_post函数调用到其他帖子中,以便在同一页面中同时使用它们我叫第一个get_post(主帖子),我只获得第二个数据,而无法到达第一个数据。 我的代码调用了第二个功能(第一个功能来自wordpress帖子):

    $main_post = get_field('main_post');
    $main_p = get_post($main_post->ID);

然后,我尝试使用变量 $post the_title()或任何其他函数来获取第一篇文章,并且它总是返回{{1} }帖子

例如

$main_p

返回get_the_title( get_post()->ID ) 帖子ID,而不是single.php的主要帖子

有什么灵魂幻想吗?

2 个答案:

答案 0 :(得分:0)

我可能是错的,但是在我看来,您正在尝试发布与普通帖子格式不同的帖子格式?

我,我自己使用get_post_format(),因此可以设置不同的样式或具有不同的选项。

在single.php中,我使用

     <!-- checking if there are any blogposts to be shown using have_posts check which is a wordpress function-->
      <?php if(have_posts()) : ?>
       <?php while(have_posts()) : the_post(); ?> <!-- the correct syntax for while loop in wordpress to show all the blogposts -->

        <?php get_template_part('content', get_post_format()); ?>

       <?php endwhile; ?>

      <?php else : //else stament if there aren't any posts (put inside if before endif)?>
       <p><?php __('No Posts Found'); ?></p>

      <?php endif; ?> <!-- stop checking for blog posts-->

    </div><!-- /.blog-main -->

在functions.php内部,我激活了wp_theme_setup()函数中的后格式

add_theme_support('post-formats', array('aside', 'gallery'));

在这种情况下,我激活了画廊并保留了帖子

这样,我在一页上有2种不同的帖子类型

像这样 image from my theme blog page

这也是有关Traversy媒体发布格式的视频教程 https://www.youtube.com/watch?v=CRa7eiqyiCM&list=PLc5p9nvpdwBlrNU0hr1f0kXPRkh0aGo1Q&index=7

答案 1 :(得分:0)

帖子值被覆盖的主要原因是,附加的get_post()声明将覆盖默认查询。现在,您的pastebin中的代码简直是累死了,所以直接的解决方案是一项艰巨的任务(例如,缩进无处不在,代码片段在可读性方面并不理想)。但是,我可以为您指出解决方案的正确方向。

当我从WordPress网站上的另一个页面提取内容时,我避免使用get_post()来声明一个新的new WP_Query()(这只是我的偏爱),然后再跟一个{{1} }声明。

这是WordPress代码库中单个模板上多个查询的示例:

https://codex.wordpress.org/Class_Reference/WP_Query#Multiple_Loops

此处的密钥是wp_reset_postdata()。我建议您调查一下它的目的。这样可以省去很多麻烦:

https://codex.wordpress.org/Function_Reference/wp_reset_postdata