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.
CodePudding user response:
Just use a variable (e.g. $imported, initial value=0) to check the counts. If imported, increment it .
So at last if the variable is still 0, call the echo statement
Hence:
<?php
echo "Page: " . $page_placement . "/" . $total_pages . "\n\n";
$imported=0;
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";
$imported ;
}
}
if ($imported==0){
echo "No record imported";
}