iMarkDesigns iMarkDesigns - 2 months ago 6
PHP Question

WordPress Covert post ID in loop to array

Issue:

Wanted to create an array using all

$post->ID
from all of my published articles. However in my WordPress, I have
$tokenID
which is the key to display certain article if matched to
$post->ID
.

Code Fig. 1

$tokenID = 244;

$io_ID = new WP_Query( ['post_type' => 'sdm_downloads', 'posts_per_page' => -1] );
while ( $io_ID->have_posts() ) : $io_ID->the_post();

print_r($post->ID);

endwhile;
wp_reset_postdata();


Result: 255254253251244

This is what the
$post->ID
when I echoed inside
while()
loop, where it should be 255, 254, 253, 251, 244


I tried
str_split
and result almost near to what i wanted to achieve. Here's the output.

Code Fig. 2

$tokenID = 244;

$io_ID = new WP_Query( ['post_type' => 'sdm_downloads', 'posts_per_page' => -1] );
while ( $io_ID->have_posts() ) : $io_ID->the_post();

$arr2 = str_split($post->ID, 3);
// print_r($arr2);

if( in_array($tokenID, $arr2) ) {
$set = 'true';
} else {
$set = 'false';
}

endwhile;
wp_reset_postdata();

echo $set;


Result of print_r: Array ( [0] => 255 ) Array ( [0] => 254 ) Array ( [0] => 253 ) Array ( [0] => 251 ) Array ( [0] => 244 )

Result of condition: "true"

*Even if the
$tokenID
is different,
$set
output still resulted to
true
.

Question

How can I achieve to create a conditional arrangement of my
$post->ID
while it was converted to array? I want to look and match first the
$tokenID
and
$post->ID
if the value is exist before I post the article.

Answer

Maybe help for this solution!

$tokenID = 244; 
$all_posts = get_posts('post_type=sdm_downloads');
$all_id = array();
foreach( $all_posts as $all_post ) {
$all_id[] = $all_post->ID;
}
//$arr2 = str_split($all_titles, 3);
if( in_array($tokenID, $all_id) ) {
    $set = 'true';
  } else {
    $set = 'false';
  }
echo $set;