【问题标题】:Wordpress: (un-)related post that is not in current post tagWordpress:不在当前帖子标签中的(不)相关帖子
【发布时间】:2018-12-11 14:57:37
【问题描述】:

我在帖子底部显示具有相同标签的相关帖子,但我还想添加一个没有标签的随机帖子,例如“尝试这个完全不同的东西”。

我已尝试使用 tag__not_in,但我的代码不起作用:

$tag_id = get_queried_object()->term_id;
$args = [
    'post__not_in'        => array( get_queried_object_id() ),
    'tag__not_in'         => array( $tag_id ),
    'posts_per_page'      => 1,
    'orderby'             => 'rand'
];
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
        while( $my_query->have_posts() ) {
            $my_query->the_post(); ?>

对不起,我真的不知道如何编码,我只是尝试理解 Wordpress 的代码以及如何修改它。

如何将帖子标签 id 放入数组中?

更新>这有效:

global $post;
$posttags = get_the_tags();
if ($posttags) {
  foreach($posttags as $tag) {
// just the test   echo $tag->slug; 
$tag = get_term_by('name', $tag->slug, 'post_tag');
$args = array(
    'posts_per_page' => 1,
    'tag__not_in' => array($tag->term_id),
    'orderby' => 'rand',
     );
  }
}
$query = new WP_Query($args);

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    你遇到了什么错误?

    无论如何,我认为您不需要 'post__not_in',因为 'tag__not_in' 会为您解决这个问题。

    之后,我会查看$tag_id = get_queried_object()->term_id; 并确保您将所需的值分配给该变量。在某处回显 $tag_id 并确认它是您想要的。

    最后,我认为您需要将new wp_query( $args ); 设为new WP_Query( $args );

    【讨论】:

    • 这正是我的问题,我无法回显id,我可以回显名称echo $tag->name . ' '; ,但不能回显id。
    • 使用get_the_tags();(但仍处于后循环中)而不是get_queried_object() 这将返回一个对象数组,您可能需要将其转换为@987654330 的ID 数组@上班。
    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多