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

admin2025-06-03  3

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.

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.

Share Improve this question edited Feb 4, 2019 at 13:28 fuxia 107k39 gold badges255 silver badges461 bronze badges asked Feb 4, 2019 at 13:27 Jason Is My NameJason Is My Name 3782 gold badges7 silver badges21 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Instantly figured this out once I posted this - anyone who is struggling in the future:

'posts_per_page' => "'" . $number_of_blog_posts . "'",

Thanks, Jason.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748945027a315044.html

最新回复(0)