1

I'm trying to scrape a price with simple html DOM and set it as regular product price in Woocommerce.

Here is my actual code:

//Starting scrape
$html = file_get_html('http://sitenam.com/page-1/');
$price = $html->find('span[class="price"]', 0)->innertext;
//Starting post
$post = array(
    'post_author' => 1,
    'post_content' => 'Content Here',
    'post_status' => "publish",
    'post_title' => "Product Title Here",
    'post_parent' => "product-title-here",
    'post_type' => "product",
);

$post_id = wp_insert_post( $post, $wp_error ); 

wp_set_object_terms( $post_id, 'simple', 'product_type' );  

add_post_meta( $post_id, '_regular_price', $price );

The product price is really saved as you can see in this image:

Product Price

But the real problem is that the product price is not displayed on front end. Here's the screenshot:

Product Price Not showing

Now on admin edit product page, if I click on "update" button, then the price is displayed on frontend product pages.

How can I automate this process from my code, without going in backend saving the product data?

4
  • Are you trying to reinstalling the plugin and theme?
    – Ram kumar
    Sep 19 '19 at 6:32
  • Yes, I tried it also bro...
    – Shaad Amin
    Sep 19 '19 at 7:28
  • are you Test your website in another theme, is it work properly or not, Are you install any third-party plugin like paytm ,sometimes its causes this type of problem, when i face this problem i just wipe my site and reinstall all the thinks , you try this ,Open your site’s wp-config file and add define( 'WC_REMOVE_ALL_DATA', true); on its own line above the /*
    – Ram kumar
    Sep 19 '19 at 7:49
  • It's not worked bro. I tried everything :(
    – Shaad Amin
    Sep 19 '19 at 9:45
2

Try the following using the WC_Product Object and methods instead:

// Starting scrape
$html = file_get_html('http://sitenam.com/page-1/');

$price = (float) $html->find('span[class="price"]', 0)->innertext;

// Saving the new product
$post_id = wp_insert_post( array(
    'post_author' => 1,
    'post_content' => 'Content Here',
    'post_status' => "publish",
    'post_title' => "Product Title Here",
    'post_parent' => "product-title-here",
    'post_type' => "product",
) ); 

// Setting the product type
wp_set_object_terms( $post_id, 'simple', 'product_type' );  

// Get the WC_Product Object instance
$product = wc_get_product( $post_id );

// Set the product active price (regular)
$product->set_price( $price );
$product->set_regular_price( $price ); // To be sure

// Save product data (sync data and refresh caches)
$product->save();

This time the product price should be displayed in front end.

1
  • Thank you so much... It worked... Love you bro
    – Shaad Amin
    Sep 20 '19 at 13:58

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.