I would like to make wordpress plugin with woocommerce. My idea was making something like crowdfunding (displaying earned money, target money etc.). I made a script that gets the ID of product but when I try to use wc_get_product($id) i get errors "Call to undefined function wc_get_product()". I tried including woocommerce.php file but then I got "wc_get_product should not be called before the woocommerce_init, woocommerce_after_register_taxonomy
and woocommerce_after_register_post_type actions have finished."
Main file:
<?php
/**
* Plugin Name: xxx
* Plugin URI: xxx
* Description: xxx
* Version: xxx
* Author: xxx.com
* Author URI: xxx
*/
defined( 'ABSPATH' ) or die( 'Plugin file cannot be accessed directly.' );
/* prevents submit button from sendind the same data twice (off for now)
function preventResubmit(){
?>
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
<?php
}
*/
require(dirname(__FILE__).'/shortcodes.php');
add_action("admin_menu","cfdg_add_admin_menu");
function cfdg_add_admin_menu(){
add_menu_page("Crowdfunding","Crowdfunding", "manage_options", "cfdg-admin", "cfdg_add_page", "dashicons-money");
}
function cfdg_add_page(){
require (dirname(__FILE__).'/adminmenu.php');
}
?>
shortcodes.php
<?php
$earnedMoney = cfdg_getEarnedMoney();
$targetMoney = 30000;
function cfdg_getEarnedMoney() {
global $wpdb;
$cdfg_money_to_return = 0;
$sql = 'SELECT ml.product_id FROM wp_wc_order_product_lookup AS pl
JOIN wp_wc_product_meta_lookup AS ml ON pl.product_id = ml.product_id
JOIN wp_posts AS wp ON wp.ID = pl.order_id WHERE LOCATE("crowdfunding",sku) AND (wp.post_status = "wc-processing" OR wp.post_status = "wc-completed");';
$results = $wpdb->get_results($sql);
if(!$results) return 0;
foreach($results as $res){
$cdfg_produkcik = wc_get_product($res); /* <--- HERE I GET THE ERROR */
$cdfg_product_price= $cdfg_produkcik->get_price();
$cdfg_money_to_return += $cdfg_product_price;
}
return $cdfg_money_to_return ;
}
//PROGRESS BAR
add_shortcode('cfdg_progress_bar', 'cfdg_func_progress_bar');
function cfdg_func_progress_bar(){
global $earnedMoney; global $targetMoney;
echo "Earned: ".$earnedMoney." from: ".$targetMoney." required";
}
//END OF PROGRESS BAR
?>
2
Answers
You need to define the global WooCommerce variable.
You can also use