php - 如何获取博客存档年份选择以更新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 所以可以重新加载页面
解决方案
假设您使用的是标准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');
}
然后您可以调用此函数将年份添加到您的查询中。
推荐阅读
- python - 如何使用生成器训练 XGBoost?
- powerbi - 根据在 Power BI 中搜索单独字段查找周围的索引记录
- react-native - chrome调试器打开时反应本机应用程序崩溃
- spring-boot - 是否可以在运行时重新启动 Hikari 数据源
- javascript - 按键顺序对对象进行分组
- node.js - 使用 Prisma 进行深度嵌套事务写入
- python - 并行 Python 代码在 Replit 上运行良好,但在本地失败
- typescript - 使用自定义节点模块在 RTL 中运行意外令牌“导出”测试
- python - 将基本物理实现到一个简单的 2d pygame(仅限惯性和重力)
- ansible - 如何使用字典设置_facts,我在哪里引用库存项目?