To ensure that the checkposts
function works properly within a WordPress hook action, you can define the checkposts
function outside the populate_inventory
function. This approach keeps the code organized and ensures that the function is available when needed. Here’s the revised version of your code:
add_action( 'populate_inventory_hook', 'populate_inventory' );
function populate_inventory() {
$url="https://website.com/webfeed?version=2";
// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Set the url
curl_setopt( $ch, CURLOPT_URL, $url );
// Execute
$result = curl_exec( $ch );
// Closing
curl_close( $ch );
$items = json_decode( $result, true );
$feed_count = count( $items );
$check_counter = 0;
$exist_counter = 0;
$non_exist_counter = 0;
$wp_args = array(
'post_type' => 'wheelchair-vans-sale',
'posts_per_page' => -1,
'post_status' => 'publish',
);
$query = new WP_Query( $wp_args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
$check_counter++;
if ( checkposts( $items, $post->ID ) ) {
echo "1";
$exist_counter++;
} else {
echo "0";
$non_exist_counter++;
}
endwhile;
echo "<br />";
wp_reset_postdata();
endif;
}
function checkposts( $items, $postid ) {
global $post;
$wp_vin = get_post_meta( $postid, "item_vin", true );
$i = 0;
foreach ( $items as $item ) {
if ( $item['vin'] == $wp_vin ) {
$i++;
}
}
if ( $i < 1 ) {
wp_delete_post( $postid );
}
return $i;
}
In this setup, the checkposts
function is defined separately and is called within the populate_inventory
function to perform the necessary checks. This structure ensures that all functions are properly defined and accessible when the hook is executed.