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

Time:04-28

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;

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

CodePudding user response:

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,
) );
  • Related