Return array php

So I can’t seem to understand why I can’t return my array

Call to the function

Read More
<?php

$args = array( 'post_type' => 'product', 
                'stock' => 1, 
                'posts_per_page' => 12, 
                'meta_key' => 'total_sales',
                'orderby' => 'meta_value_num' );

productsLoop($args);

?>

The function located in functions.php

function productsLoop($args){

$post_ids = array();
    $loop = new WP_Query( $args );
    if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();


    $post_ids[] = get_the_ID();


    endwhile;
    } else {
    echo __( 'No products found' );
    }

    wp_reset_query();
    return $post_ids;
}

Then on the original page I use the $post_ids in a for each loop, however it returns the error of undefined varibale

Related posts

1 comment

  1. The $post_ids variable isn’t available outside of the function. Since the function returns the array of IDs, you can assign that return value to a variable and use it in your loop.

    $ids = productsLoop($args);
    // you can use the $ids variable now, for example...
    foreach ($ids as $id) {
        echo $id . '<br>';
    }
    

    Have a read through the variable scope section of the PHP manual for details.

Comments are closed.