Function – Automatically remove posts that are not in an array

I’ve written a function that I linked to a CRON job that creates posts for a custom post type every 6 hours fed from an XML feed. The issue is that sometimes records are deleted and these deleted records need to be reflected as well.

I’ve written a function that does it, but I’m concerned about the efficiency of the function, mainly that it foreach through the xml feed to grab the post titles and build the array, then it loops the get_post and A foreach through that loop.

I guess what I’m asking for is a sanity check and see if there’s a better way.

$feed = file_get_contents('samplexml.xml');

        $titles = simplexml_load_string($feed); 

        $titlesarray = array();

        foreach($titles as $title){
            $name = (string)$title->id;
            $titlesarray[] = $name;

        //print_r ($titlesarray);

        $args = array(
            'numberposts' => -1,
            'post_type' => 'custompost',
        $customposts = get_posts( $args );

        foreach ($customposts as $custompost) {
            $customid = $custompost->ID;

            $customname = get_the_title($customid);

            $exists = false;

            foreach($titlesarray as $arraytitle){
                if( $customname == $arraytitle ){
                    $exists = true;

            if($exists == true){
                //echo 'exists<br />';
            } else {
                echo 'delete<br />';


Leave a Comment