So I can't seem to figure out this logic, so I'm reaching out to see if someone might be able to help me.
So I have the following foreach
:
echo "Page: " . $page_placement . "/" . $total_pages . "\n\n";
foreach ($posts as $post) {
$current_post_id = post_exists(
$post->title->rendered,
'',
'',
'',
''
);
if ($current_post_id === 0) {
$my_post = [
'post_type' => 'post',
'post_status' => 'pending',
'post_title' => wp_strip_all_tags($post->title->rendered),
'post_content' => wp_strip_all_tags($post->content->rendered),
'post_excerpt' => wp_strip_all_tags($post->excerpt->rendered),
'post_author' => 1,
'post_date' => $post->date,
];
// Insert post.
$post_id = wp_insert_post($my_post);
wp_set_object_terms($post_id, 'Global', 'category');
wp_set_object_terms($post_id, 'Global', 'post_tag');
echo "ID: " . $post->id . " - Title: " . $post->title->rendered . " has been imported.\n";
}
}
It grabs 50 $posts
and then loops through and calls post_exists()
to check the title of the post, and if it doesn't exist, it will import the post otherwise it will skip it.
How can I display an echo message if all 50 of the posts aren't imported?
I can't call if (!$current_post_id) {
inside the foreach, as it will display the message 50 times and I tried to play an variable outside the foreach
and then call $my_post[] = [ .... ]
but then the wp_import_post
didn't work.
My Answer:
"Starting foreach loop...";
foreach ($array as $item) {
// do something with $item
}
echo "Foreach loop completed.";
if (empty($array)) {
echo "The foreach loop did not return any items.";
} else {
echo "The foreach loop returned items.";
}
Rate this post
4 of 5 based on 4184 votesComments