微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WooCommerce 产品:自定义循环中的错误产品永久链接

如何解决WooCommerce 产品:自定义循环中的错误产品永久链接

我正在使用自定义循环来显示一系列产品。 循环工作正常,并显示具有正确标题、图像和其他内容的产品。 但永久链接当前页面的 URL。

如果我在永久链接添加 $post,一切正常:get_permalink($post)

这是我当前的代码

<?PHP $featured_posts = $products_select; if( $products_select ): ?>
<div>
    <ul>
        <?PHP foreach( $featured_posts as $post ): setup_postdata($post); ?>
            <?PHP wc_get_template_part( 'content','product' ); ?>
        <?PHP endforeach; ?>
    </ul>
    <?PHP wp_reset_postdata(); ?>
</div>

我检查了 $products_select内容,发现没有存储链接。 这可能是问题吗?有什么办法可以纠正永久链接吗?

变量 $products_select 是基于 relationship field from Advanced Custom Fields自定义字段输出。它存储为 post 对象。

解决方法

更新

不要使用 get_posts() 函数,而是使用真正的 WP_Query,如下例所示:

<?php
$loop = new WP_Query( array(
    'post_status' => 'publish','post_type' => 'product','posts_per_page' => 10,) ); 
?>
<div>
    <ul><?php
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
    echo '<pre>ID: '.get_the_id().' | Title: '. get_the_title() . ' | Link: ' . get_permalink() . '</pre>';
    wc_get_template_part( 'content','product' );
endwhile;
wp_reset_postdata();
endif;?>
    </ul>
</div>

这次可以正常工作,没有任何问题。


替代方法:为避免此问题,您可以改为使用 WooCommerce [products] 短代码,如下所示:

<?php 
$featured_posts = $products_select; if( $products_select ): 

// get a comma separated string of product Ids
$post_ids = implode( ',',wp_list_pluck( $featured_posts,'ID' ) ); 

// Use [products] shortcode with the comma separated string of product Ids
echo do_shortcode("[products ids='$post_ids']" ); ?>
</div>

经过测试并有效。

,

我还发现了一个可以使用高级自定义字段并保持关系字段的自定义顺序的解决方案:

<?php
$args = array(
    'post_type' => 'product','post__in' => $products_select,'posts_per_page' => 4,'orderby' =>  'post__in' 
    );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) : ?>
<div>
    <ul>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <?php wc_get_template_part( 'content','product' ); ?>
        <?php endwhile; ?>
    </ul>
</div>  
<?php endif;  wp_reset_postdata(); ?>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。