首页 > 解决方案 > 如何获取博客存档年份选择以更新functions.php中的全局变量

问题描述

我在模板中有一个下拉选择,我希望根据从 WP 档案列表中按年份选择来更新我在函数文件中设置的全局变量的值。

落下

<div>
        <select style="top: -4px;"
                class=" btn-link col-12"
                name="archive-dropdown"
                onChange='document.location.href=this.options[this.selectedIndex].value;'>
            <option value=""><?php esc_attr( _e( 'Select From Archive', 'textdomain' ) ); ?></option>
            <?php wp_get_archives( array( 'type' => 'yearly', 'format' => 'option', 'show_post_count' => 1 ) ); ?>
        </select>
    </div>

函数全局变量

    function test() {
    global $CurrentYear;
    $CurrentYear = '2018';
}
add_action( 'after_setup_theme', 'test' );

我在我的查询中使用这个 var 来显示帖子,选择的年份应该通过下拉设置并更新全局 var 依次更新要显示的年份。

我的目标 下拉列表中选择的年份只是更新全局变量的年份值。

注意 没有 Ajax 所以可以重新加载页面

标签: phpwordpress

解决方案


假设您使用的是标准archive.php模板,您可以执行以下操作:

  • 用于is_year()检查查询是否针对一年的存档
  • 然后使用get_the_time('Y')从发布日期获取年份
  • 您可以用于这些在您的add_action函数中工作的最早的钩子是parse_query.

综上所述,您只需将以下内容添加到您的functions.php

function set_year_from_archive() {
    global $CurrentYear;

    if (is_year())                         // if we're querying for the archive by year
        $CurrentYear = get_the_time('Y');  // get the year and set your variable
}
add_action( 'after_setup_theme', 'set_year_from_archive' );

注意:您可以使用函数返回当前年份(如下所示),而不是使用全局变量(通常不鼓励),然后在查询中需要年份的地方调用它吗?例如将其添加到functions.php

function get_year_from_archive() {
    if (is_year())  
        return get_the_time('Y');
}

然后您可以调用此函数将年份添加到您的查询中。


推荐阅读