Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Doesn't Variable Work When I Assign It In Array?

I need to use a variable in the below code but it doesn’t work, I don’t understand why.

Working code;

$the_query = new WP_Query( array(
    'post__in' => array(
        16405,16362,16290,16434,16661
    ),
) );

Code that doesn’t work;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$featured_content_id = get_theme_mod( 'laura_featured_content_id' );
$the_query = new WP_Query( array(
'post__in' => array(
$featured_content_id
),
) );

When I look at $featured_content_id variable using echo and var_dump(), it seems to be correct. Which means the result is 16405, 16362, 16290, 16434, 16661 but it doesn’t work inside a array. Also it doesn’t work if I directly use $featured_content_id = ‘16405, 16362, 16290, 16434, 16661’. Do I have to write it inside array?

>Solution :

Assuming $featured_content_id is a string:

You probably want explode(',', $featured_content_id) and not array($featured_content_id). And in case it has to be a number and not a string, you’d also need array_map('intval', ...) around it.

This is because what you currently do will give you an array like array('16405,16362,16290,16434,16661') which is an array with one element that is a string. What you actually want is to split the string (using , as separator) into an array with one element for each part.

$the_query = new WP_Query( array(
    'post__in' => array_map('intval', explode(',', $featured_content_id)),
) );

Assuming $featured_content_id is an array:

If it’s already an array, all you need is to pass the variable directly, without wrapping it in array( ).

$the_query = new WP_Query( array(
    'post__in' => $featured_content_id,
) );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading