【问题标题】:Get a variable from one wordpress template file to another从一个wordpress模板文件中获取一个变量到另一个
【发布时间】:2011-06-12 13:49:39
【问题描述】:

我有一个模板文件 (trendingPosts.php) 用于显示 2 个带有“趋势”标签的最新帖子。在显示这 2 个帖子的 while 循环中,我将它们的 ID 放在一个数组中,以便稍后将它们从主 wordpress 循环中排除:

<div id="trendingWrap" class="clearfix">

<?php
$trending = new WP_Query();
$trending->query("showposts=2&tag=trending");
while($trending->have_posts()) : $trending->the_post();
$wp_query->in_the_loop = true;
$currentTrending[] = $post->ID;
?>

    <div class="trendingStory">
        <h2 class="trendingTitle"><a href="<?php the_permalink(); ?>" alt="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
    </div><!-- end trendingStory -->

<?php endwhile; ?>

</div><!-- end trendingWrap -->

问题是我有一个 index.php,其中我通过 get_template_part( 'loop', 'index' ); 包含 loop.php 并且我无法获得 $currentTrending[] 数组我在 trendingPosts.php 中制作的。 我需要在我的 loop.php

中获取该数组

另外,在我的loop.php中,我排除了以下2个帖子。

if(have_posts()): while(have_posts()) : the_post(); 
    if( $post->ID == $currentTrending[0] || $post->ID == $currentTrending[1] ) continue;

这是排除帖子的正确方法吗?如果有人有更好的方法来做这件事。请告诉我。 当然,在我设法在 loop.php 中获取该数组之前,没有任何效果,所以这是主要问题。

谢谢!感谢所有帮助。

【问题讨论】:

  • 非常感谢您的回复,但下面的方法对我有效,我的代码几乎没有变化。
  • 你应该把这个评论放在另一个答案的下面;)投票总是一种很好的表达感谢的方式(小提示)。

标签: php wordpress-theming wordpress


【解决方案1】:

您可以使用$GLOBALS superglobal 数组轻松创建可以随处访问的变量。

一次设置

$GLOBALS['mytheme_thisismyvar'] = 22;

然后您可以在其他模板中的任何位置访问它:

$myvar = $GLOBALS['mytheme_thisismyvar'];

并在适合的地方使用它。这适用于子模板,无论它们如何加载。

因为整个程序共享这个超全局数组,请注意不要覆盖现有值。

【讨论】:

  • 太棒了!那行得通……最好的部分:我不必更改我的代码。
【解决方案2】:

尝试将您当前的趋势代码移动到主题的functions.php,以便您可以在需要时调用它。

function getCurrentTrending() {
  $trending = new WP_Query();
  $trending->query("showposts=2&tag=trending");
  while($trending->have_posts()) : $trending->the_post();
    $wp_query->in_the_loop = true;
    $currentTrending[] = $post->ID;
  endwhile;
  return $currentTrending;
}

然后您可以从任何模板文件中获取该数组:

$currentTrending = getCurrentTrending();

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 2011-11-28
    • 2011-07-06
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多