如何根据正在引用的当前帖子拉出帖子对象?

问题描述

我为商品视频设置了一个自定义帖子类型,称为“电视”,并在自定义字段添加一个将商品称为帖子对象的字段。

我现在想进行反向工程,以便在该字段中引用产品时,在产品页面上会出现指向正确视频的链接。这是我到目前为止所拥有的:

<?PHP

    $thisinstrument = get_post($post->ID,$output = OBJECT,$filter = 'raw');
    
    $posts = get_posts(array(
    'numberposts'   => -1,'post_type'     => 'tv','Meta_key'      => 'instruments','Meta_value'    =>  $thisinstrument
    
    ));

    if( $posts ): ?>
    
    <!-- TV -->
    
    <ul>
        
    <?PHP foreach( $posts as $post ): 
        
        setup_postdata( $post );
        
        ?>
        <li>
            <a href="<?PHP the_permalink(); ?>"><?PHP the_title(); ?></a>
        </li>
    
    <?PHP endforeach; ?>
    
    </ul>
    
    <?PHP wp_reset_postdata(); ?>

    <?PHP endif; ?>

我认为我是对的。首先我将$ thisinstrument设置为get_post($ post ='null',$ output = OBJECT,$ filter ='raw');并且只打印了所有帖子。

我要去哪里错了?

解决方法

我假设“'meta_key'=>'instruments'”应该包含当前帖子的ID,因此当您查询$ thisinstrument时,应该使用$ post-> ID。 我相信以下代码可以帮助您完成此任务。

<?php
    
    // $thisinstrument =.... No need for this line if the 'instruments' field is the ID of the current post,we can just insert that inside the get_posts() below.

  GLOBAL $post;
  $posts = get_posts(array(

    'numberposts'   => 1,'post_type'     => 'tv','meta_query'    => array(
        array(
            'key' => 'instruments','value' => $post->ID,)
    )
));

if( $posts ): ?>

<!-- TV -->

<ul>
    
<?php foreach( $posts as $post ): 
    
    setup_postdata( $post );
    
    ?>
    <li>
        <a href="<?php the_permalink($post->ID); ?>"><?php the_title($post->ID); ?></a>
    </li>

<?php endforeach; ?>

</ul>

<?php wp_reset_postdata(); ?>

<?php endif; ?>

我相信应该这样做,尝试一下,让我知道我可能读错了你的意思。