【问题标题】:get_template_part - Wordpress not workingget_template_part - WordPress 不工作
【发布时间】:2020-11-12 21:19:34
【问题描述】:

我正在尝试将 about 页面的内容放在标题的 div 中,模板部分位于文件夹 template-parts/content-about.php

在标题上的代码是:

<div id="slideOut"> 
<div class="slideout-content">

    
    <?php
    while ( have_posts() ) :
        the_post();

        get_template_part( 'template-parts/content', 'about' );

    endwhile; // End of the loop.
    ?>
    
      <?php include 'content-about.php'; ?>
</div><!-- .slideout-content -->
</div>  

content-about.php 看起来像这样:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="entry-content">
    <?php
    the_content();

    wp_link_pages(
        array(
            'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'about' ),
            'after'  => '</div>',
        )
    );
    ?>
</div><!-- .entry-content -->
</article><!-- #post-<?php the_ID(); ?> -->

问题是在 div 上显示与当前页面相同的内容,例如,如果我位于主页上,它只显示 div 内的主页内容,而它应该始终显示关于页面。 为什么不工作? 谢谢

【问题讨论】:

  • 因为您的content-about.php 中没有任何内容告诉它从该页面获取内容。如果你查看你的文件,你使用的是the_content()。由于它在循环中,因此它将从您所在的任何页面获取内容。您可以使用get_the_content() 并将关于页面id 传递给该函数。仅仅因为文件被命名为content-about 并不意味着它会从该文件中获取内容。
  • 谢谢你能给我举个例子吗,我是wordpress这部分的新手。
  • 当然。我会添加一个答案。

标签: php wordpress


【解决方案1】:

get_template_part() 正在按预期工作。您的content-about.php 正常包含在内。

但是,它会打印当前帖子/页面的内容,因为您正在调用the_content()

您可以将 the_content() 替换为 get_the_content(),将您的 about 页面的帖子 ID 作为第三个参数传递。

注意:

the_content() 的一个重要区别是get_the_content() 不会通过the_content 过滤器传递内容。这意味着get_the_content() 不会自动嵌入视频或扩展短代码等。

因此,您可能希望像这样使用apply_filters()

<?php
echo apply_filters( 'the_content', get_the_content( null, false, $about_page_id ) );
// where $about_page_id is the post id of your about page

【讨论】:

  • 谢谢,这是一个很好的解决方案,因为我在 about 页面上放置了一个视频,该视频也需要显示在标题滑块中
【解决方案2】:

如果你不想要,你甚至不需要get_template_part

你可以这样做:

<div id="slideOut"> 
    <div class="slideout-content">
        <?php echo get_the_content('','','your-about-page-id-here'); ?>
    </div><!-- .slideout-content -->
</div>  

get_template_part() 是一种包含带有标记的文件的方法,该标记可能依赖于循环,但将内容分开。这里不一定需要它。

您还可以使用: echo get_post_field('post_content', your-post-id-here );

【讨论】:

  • 您应该将about页面id作为get_the_content()的第三个参数传递。另外,请注意get_the_content() 不会通过the_content 过滤器传递内容。
  • 正确。但是,我猜 OP 试图做的事情中没有视频或 iFrame,因为这看起来像一个标题滑块。
  • 谢谢,效果很好,但我在 about 页面上有视频
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
  • 2013-03-12
  • 2011-08-14
  • 1970-01-01
相关资源
最近更新 更多