0

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.

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.

| improve this answer | |
  • You don't need the "'" around the number. – fuxia Feb 4 '19 at 13:52
  • Thanks @fuxia. This works now, I believe. But I am unable to save my page when I update this variable value in the backend. It just says saving for ages (tested up to an hour). – Jason Is My Name Feb 4 '19 at 14:49
  • Your answer wasn't wrong, it just had some code that wasn't necessary. I don't really see what to discuss. :) – fuxia Feb 4 '19 at 15:13
  • @fuxia - I was having an issue with using an outdated version of the plug in ACF - Advanced Custom Fields. Now I have updated this it works swimmingly! Thanks for your persistence and politeness! – Jason Is My Name Feb 4 '19 at 15:36
  • You shouldn't need to add quotes around the variable. What output do you get if you do var_dump($number_of_blog_posts). You can also cast the variable using 'posts_per_page' => (int)$number_of_blog_posts, – Alexander Holsgrove Feb 4 '19 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.