Skip to main content
1 of 2

Using a variable within the blog posts array query - posts_per_page as variable

I am trying to use a variable that my content person can change when editing pages to display a different number of blog posts.

Here I have declared the variable:

<?php
while( have_rows('social_grid_settings') ): the_row();
    $number_of_blog_posts = get_sub_field('number_of_blog_posts');
?>

This has been checked and the variable is correct.

However when placed inside the query it doesn't seem to register it and displays all posts:

<?php
$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'social-grid',
    'posts_per_page' => $number_of_blog_posts,
);
$arr_posts = new WP_Query( $args );

If I state a static figure '1' instead fo the variable it works.

Am I allowed to use a variable in this way?

Can anyone help me get this variable acting as it should?

Thanks, Jason.