0

I'm sorry for my english. I'm trying to add some functionalities at my Wordpress website and to do this i have added a function in my function.php theme. The idea is to save in a custom table some datas and create a wp_post for any element added in the custom table.

I hooked the function in this way:

add_action ( 'init', 'inserimentoAutoDatabase' );

The problem is that when the function is executed the query that save the datas in the custom table and create a new post is executed twice. I report my code:

function inserimentoAutoDatabase(){

    //get datas from an xml file
    $result = fetchData("http://dealer.drivek.it/myPortalXML/index?myPortalXMLkey=d660d1e9-8c1d-41ff-8f54-0829777a9960");

    //save the xml  
    $fp = fopen('autodealerk-1.xml', 'w+');
    fwrite($fp, $result);
    fclose($fp);

    //load xml file
    $xml=simplexml_load_file("autodealerk-1.xml");

    $i=0;

    //start parsing xml content
    foreach($xml->car as $auto)
    {
        //this echo is executed only once
        echo ("test");

        //not important for the question | checks some content
        if($auto->km == null || $auto->km  == ''){
            $kilometri = "nuova";
            $anno_registrazione = "-";
        }else{
            $kilometri = $auto->km;
            $anno_registrazione = $auto->registrationDate;
        }

        $inevidenza = 0;
        if($auto->tractionType){
            $inevidenza = 1;
        }


        // create an array for the query
        $insData = array(
            'id' => $auto['id'],
            'make' => (string) $auto->make,
            'model' => (string) $auto->model,
            'version' => (string) $auto->version,
            'bodyType' => $auto->bodyType,
            'fuelType' => $auto->fuelType,
            'type' => $auto->type,
            'dealer_name' => (string) $auto->dealer->name,
            'gear_gearType' => (string) $auto->gear->gearType,
            'tractionType' => $auto->tractionType,
            'kw' => $auto->kw,
            'doors' => $auto->doors,
            'seats' => $auto->seats,
            'emissionClass' => $auto->emissionClass,
            'prices_listPrices' => $auto->prices->listPrice,
            'exterior_color_paint' => $auto->exterior->color . " " . $auto->exterior->paint,
            'km' => $kilometri,
            'typewarrantyMonths' =>  $auto->warranty->type . " " . $auto->warranty->warrantyMonths,
            'equipments' => "equipaggiamenti",
            'media' => $auto->image,
            'description' => $auto->description,
            'registrationDate' => $anno_registrazione
        );

        $wpdb->insert('auto_importate', $insData);


        // define the post
        $my_post = array(
          'post_title'    => (string) $auto->make . (string) $auto->model . (string) $auto->version,
          'post_content'  => $auto->description,
          'post_status'   => 'publish',
          'post_author'   => 1,
          'post_type'     => "vehicles"
        );

        // ***** post is created twice
        $post_id = wp_insert_post( $my_post );


        //i break the cycle **** only for test
        $i++;
        if( $i == 1 ) break;

    }
}

As you can see in the images below at the end of the cicle (breaked after the first execution) i expect only one element but there are twice.

auto_importate table

auto_importate table content

Anyone can help me??? Have you any idea about this issue?

Thanks in advance.

  • see this question: wordpress.stackexchange.com/q/27585/4771 – Milo Jul 8 '14 at 18:17
  • I'm sorry but it doesn't work for me – Manuel Ragazzini Jul 8 '14 at 18:51
  • @Rarst Comment is now an answer. In these instances, do I delete my comment?? – eyoung100 Jul 8 '14 at 20:16
  • @ECarterYoung mods usually do it, even if not - no harm really :) – Rarst Jul 8 '14 at 20:23
  • any additional request will trigger your code, for example a 404 on an asset served in the first request will result in another request hitting WordPress. – Milo Jul 8 '14 at 22:09
1

The use of wpdb->insert and wp_insert_post both accomplish an SQL Insert, which is why you're seeing 2 records each time. You must use only one instance of an insert method, and then Pass $my_post to WP_Query

CLARIFICATION

As Milo points out in his comment wpdb->insert will insert into any table, while wp_insert_post is used to insert a post into the wp_posts table. wpdb->insert is used mainly for custom tables.

In your case:

<?php $wpdb->insert( 'auto_importare', $insData); ?> 

Sticking with the premise that $wpdb should be used for custom tables, you would then use wpdb->get_results to select the data you just inserted:

<?php $post_results -> $wpdb->get_results( 'SELECT make,model, version,description FROM wpdb->auto_importare'); ?> 

Lastly, and this part escapes me at the moment, you would build your post query from $post_results

See The WordPress Codex: wpdb

|improve this answer|||||
  • they both insert, but the data is going into two different tables. – Milo Jul 8 '14 at 20:32
0

You make no attempt to check if the work has already been done. As a result on every page load the work will be done yet again and more posts created.

Because of this, when WordPress attempts to run WP Cron, you'll get a second load, and a second run of the code.

So do not run this on every page load via the init hook. The URL being fetched takes a long time to return the full page so your site will run very slowly.

Instead:

  • Run this in a cron job that runs at regular intervals
  • Check before inserting if the post has already been created. Perhaps by querying the auto_importate table to see if a car with that ID already exists.

A final note, you do not need the auto_importate table, use custom fields/post meta instead. You may also want to get a new portal key now that you've posted it for all to see in your question

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.