显示ACF字段中具有共同值的

问题描述 投票:0回答:1

该网站出售乐谱出版物。它有许多ACF字段,其中一个字段名为Series,同一系列中的所有出版物在该字段中将具有相同的值。在“单一产品页面”模板上,我放置了一个简短的代码(尽管最终我希望将其放在按钮中),该代码从“系列”字段中获取值,然后显示具有相同值的所有帖子的标题。我的代码如下,但没有显示所需的信息。

`function display_related_titles_by_series() {
    // Get the current post's Series value (product description page)
    $series_value = get_field('series');
    echo $series_value;

// Query posts with the same Series value
$args = array(
    'post_type' => 'product', // WooCommerce
    'meta_key' => 'series',
    'meta_value' => $series_value,
);

$related_posts = new WP_Query($args);

// Display the list of titles
if ($related_posts->have_posts()) {
    echo '<ul>';
    while ($related_posts->have_posts()) {
        $related_posts->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
    wp_reset_postdata();
} else {
    echo 'No related titles found.';
}
}
add_shortcode('related_titles', 'display_related_titles_by_series');`

据我所知,这应该没问题,但当页面加载时,什么也没有显示,甚至没有找到相关标题消息。

wordpress advanced-custom-fields
1个回答
0
投票

我决定从一个稍微不同的角度来处理这个问题,并想出了这个,将其放置在相关产品通常显示的区域。

function related_products_series_shortcode() {
global $related_posts;
    $series_value = get_field('series', $post->ID);

    // Query posts with the same Series value
    $args = array(
        'post_type' => 'product', // WooCommerce
        'meta_key' => 'series',
        'meta_value' => $series_value,
        'post__in' => $related_products,
    //  'posts_per_page' => 6,
        'columns' => 6,
    );

    $related_products = new WP_Query($args);

    if ($related_products->have_posts()) 
    {
        echo '<ul>';
        while ($related_products->have_posts()) {
            $related_products->the_post();
        echo '<li> <a href="/product/'. sanitize_title( get_the_title() ) . '">'. get_the_title() . '   </a></li>';
       };
        echo '</ul>';
}
wp_reset_postdata();

return ob_get_clean();
}
add_shortcode( 'custom_related_products', 'related_products_series_shortcode' );
© www.soinside.com 2019 - 2024. All rights reserved.