1

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

Call to the function

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

2
  • can you also post the error? Commented Jun 3, 2015 at 19:53
  • This was it -> "Notice: Undefined variable: post_ids" Commented Jun 3, 2015 at 19:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.