php - 尝试使用当前帖子的标签查询帖子
问题描述
我正在创建一个具有多个帖子关系的网站。对于我使用 wordpress 标签的帖子之间的交叉引用。现在,当我在一篇有多个标签的帖子上时,我想查询所有同时有这两个标签的帖子。所以当前帖子有'tag1'
和'tag2'
,应该有一个只有这两个标签的帖子列表
请参阅下面的代码以查看我的非工作解决方案。我认为获取当前标签 ID 的列表是个好主意。为此,我使用了 Wordpress codex 提供的标准解决方案,然后我创建了一个可以在查询中使用的自定义函数。不幸的是,这似乎不是正确的解决方案,函数 listtags 确实按预期输出了 ID。
<?php
function list_tags(){
$posttags = get_the_tags();
foreach($posttags as $tag) {
echo $tag->term_id . ' ';
}
}
$listtags = list_tags();
echo $listtags . ' ';
$tag_query = new WP_Query( array(
'post_type' => 'les',
'order' => 'ASC',
'tag__and' => array( $post_tag ),
) );
// The Loop
if ( $tag_query->have_posts() ) {
while ( $tag_query->have_posts() ) {
$tag_query->the_post(); ?>
<div class="les-container" style="background-color: red; height:200px;">
<div class="container">
<div class="row posts-align">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
</div>
</div>
<?php } wp_reset_postdata();
} else {
// no posts found
}?>
该list_tags();
功能似乎可以正常工作,因为它按预期输出标签。但是,在将其插入查询时,它似乎不起作用。它只输出所有帖子,无论标签如何。
解决方案
我有一个可行的解决方案。希望这对某人有帮助。
代码:
<?php
$tags = array();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$tags[] = $tag->term_id;
}
}
$tag_query = new WP_Query( array(
'post_type' => 'les',
'order' => 'ASC',
'tag__and' => $tags,
'post_parent' => 0,
) );
// The Loop
if ( $tag_query->have_posts() ) {
while ( $tag_query->have_posts() ) {
$tag_query->the_post(); ?>
<div class="les-container" style="background-color: red; height:200px;">
<div class="container">
<div class="row posts-align">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
</div>
</div>
<?php }
wp_reset_postdata();
} else {
// no posts found
}?>
推荐阅读
- c# - 使用 itextsharp C# 重复水印文本对角线
- c++ - OpenGL 扩展未在 Windows 上链接
- r - 检测语料库中的模式匹配
- python - 从 0 到 1 创建和映射从白色到红色的 RGB 颜色渐变
- delphi - 从资源文件加载样式 vsf 不起作用
- r - 从 R 中的 taylor.diagram 获取值
- javascript - 生成随机 id 名称
- html - 如何在 HTML 标签标签中指示一个类
- angular - 纱线工作区和角度“找不到'node_modules'目录。”
- android - 将 minSdkVersion 从 16 更新到 19 后,找不到 com.android.library 错误?