skip to Main Content

I’m using a custom loop to show a selection of products.
The loop works fine and shows the products with the correct title, image and the other stuff.
But the permalink is the URL of the current page.

If I add $post inside the permalink, everything works fine: get_permalink($post)

Here’s my current code:

<?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>

I checked the content of $products_select and saw, that there is no link stored.
Could that be the problem? Is there any way to correct the permalink?

The variable $products_select is the output of a custom field based on relationship field from Advanced Custom Fields. It is stored as post object.

2

Answers


  1. Chosen as BEST ANSWER

    I also found a soultion that will work with Advanced Custom Fields and keeps the custom order of the relationship field:

    <?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(); ?>
    

  2. Update

    Don’t use get_posts() function, instead use a real WP_Query like in the following example:

    <?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>
    

    This time it will works, without any issue.


    An alternative: To avoid this problem, you could use instead WooCommerce [products] shortcode as follows:

    <?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>
    

    Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search