保存woocommerce产品后,什么是wordpress/woocommerce挂钩? [英] what is a wordpress/woocommerce hook tha fire after a woocommerce product saved

查看:74
本文介绍了保存woocommerce产品后,什么是wordpress/woocommerce挂钩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户创建并保存一个woocommerce产品数据后,通过soap-client将它发送到邮政公司的Web服务.所以我需要一个在用户创建产品后触发的钩子.我搜索了很多东西,发现了一些单词按下和woocommerce钩子,但是它们都没有做我的工作.发送日期后,Web服务将返回应设置为产品SKU的ID.听到的是我的功能代码:(参数来自save_post_product钩子)

I want to sent woocommerce product data after user create and save one, to web service of post company via soap-client. so i need a hook that fire after user create a product. i search a lot and find some word press and woocommerce hook but none of them do my work. after sending date,web service return an id that should be set as product sku. hear is my function code: (argument are from save_post_product hook)

function productPublished ($ID , $post , $update){
$product = wc_get_product( $post->ID);
$user = get_option ('myUsername');
$pass = get_option ('myPassword');
$name = $product->get_name();
$price = $product->get_regular_price();
$weight = $product->get_weight() * 1000;
$count = $product->get_stock_quantity();
$description = $product->get_short_description();
$result = $client -> AddStuff ([
    'username' => $user,
    'password' => $pass,
    'name' => $name,
    'price' => $price,
    'weight' => $weight, 
    'count' => $count,
    'description' => $description,
    'percentDiscount' => 0
]);
$stuff_id=(int)$result->AddStuffResult;
update_post_meta($product->get_id(),'_sku',$stuff_id);
}

我使用 save_post_product 操作.用户在输入名称和价格等之前单击新产品后似乎会触发,因为发送到Web服务和sku的默认产品数据已在我输入任何数据之前生成并保存.我使用 transition_post_status 并将此代码添加到我的函数中:

i use save_post_product action. it seems like it fire after user click new product before entering name and price and etc. because default product data sent to web service and sku generated and saved before i enter any data. i use transition_post_status and add this code to my function:

if($old_status != 'publish' && $new_status == 'publish' && 
!empty($post->ID) && in_array( $post->post_type, array( 'product') )){
code...}

结果与 save_post_product 相同.我使用 publish_product 操作,结果未更改.我使用 draft_to_publish 钩子.输入产品名称和说明后,似乎会触发.名称已发送到网络服务,但价格和重量都没有.sku没有保存到数据库(为什么?).我知道在此处还有一个问题,该问题要求 save_post在帖子发布后触发并保存到数据库.但我认为woocommerce是不同的.在输入名称和描述之后,在输入价格等之前,似乎可以保存帖子.有任何建议吗?

the result was the same as save_post_product. i use publish_product action and result didn't changed. i use draft_to_publish hook. it seems to fires after i enter product name and description. name sent to web-service but price and weight didn't. sku did not saved to database(why??). i know that there is another question here that claim save_post fires after post published and save to DB. but i think woocommerce is different. it seems save post after entering name and description and before entering price and etc. any suggestion???

推荐答案

您要执行的操作是:

add_action('woocommerce_update_product', 'productPublished');

add_action('woocommerce_new_product', 'productPublished');

function productPublished($product_id){
    //...
}

您可以在以下Woo源代码中找到它们(触发它们的地方):

You can find them both (where they are triggered from) in the Woo source code here:

https://docs.woocommerce.com/wc-apidocs/source-class-WC_Product_Data_Store_CPT.html#237

实际上,我首先向后查找它们,方法是先找到保存产品的源代码所在的位置,然后在这些方法(创建/更新)中查找钩子.

I actually looked them up backwards by first finding where the source code for saving products was, and then looked for hooks in those methods (create/update).

 //found on Line 134 method create
 do_action( 'woocommerce_new_product', $id );


 //found on Line 237 method update
 do_action( 'woocommerce_update_product', $product->get_id() );

您还必须更改此行:

function productPublished ($ID , $post , $update){
    $product = wc_get_product( $post->ID);
}

收件人

function productPublished($product_id){
    $product = wc_get_product( $product_id);
   //....
}

我认为其他(缺少的)参数与您的代码无关.例如,如果它是更新或新产品,除了获取我们已经拥有的产品ID外,我也看不到使用 $ post .

I don't think the other arguments (that are missing) matter to your code. Such as if it's an update or a new product, I also don't see $post used except to get the product ID, which we already have.

更新(确定回调的参数)

如果不确定回调的参数,可以查看源代码(如我在上面所做的那样),或者可以在文档中找到它,或者作为最后的选择,可以简单地输出它们.最好的输出方法是以下3种方法之一

If you are not sure about the callback's arguments, you can look in the source code (as I did above) Or if you can find it in documentation Or as a last resort you can simply output them. The best way to output them is one of these 3

  • func_get_args() - "Returns an array comprising a function's argument list" http://php.net/manual/en/function.func-get-args.php
  • debug_print_backtrace() - "Prints a backtrace (similar to stacktrace)" https://secure.php.net/manual/en/function.debug-print-backtrace.php
  • Exception::getTraceAsString() try/catch and throw an exception to output the stacktrace http://php.net/manual/en/exception.gettraceasstring.php

这是我以WordPress建模的最小/简化工作挂钩系统构建的示例.由于测试的原因,并且当您知道它的工作原理时,实际上并不难构建:

Here is an example I built with a minimally/simplified working hook system modeled after WordPress's. For testing reasons and because it's really not that hard to build when you know how it works:

//global storage (functions, not classes)
global $actions;
$actions = [];

//substitute wordpress add_action function (for testing only) 
function add_action($action, $callback, $priorty=10, $num_args=1){
    global $actions;
    $actions[$action][] = [
         'exec' => $callback,
         'priorty'=>$priorty,
         'num_args' => $num_args
    ];

}
//substitute wordpress do_action function (for testing only) 
function do_action($action, ...$args){
    // PHP5.6+ variadic (...$args) wraps all following arguments in an array inside $args (sort of the opposite of func_get_args)
    global $actions;

    if(empty($actions[$action])) return;
    //sort by priory
    usort($actions[$action], function($a,$b){
       //PHP7+ "spaceship" comparison operator (<=>)
       return $b['priorty']<=>$a['priorty'];
    });

    foreach($actions[$action] as $settings){
        //reduce the argument list
        call_user_func_array($settings['exec'], array_slice($args, 0, $settings['num_args']));
    }
}

//test callback
function callback1(){
     echo "\n\n".__FUNCTION__."\n";
    print_r(func_get_args());
}

//test callback
function callback2(){
    echo "\n\n".__FUNCTION__."\n";
    try{
        //throw an empty exception
        throw new Exception;
    }catch(\Exception $e){
         //pre tags preserve whitespace (white-space : pre)
        echo "<pre>";
        //output the stacktrace of the callback
        echo $e->getTraceAsString();
        echo "\n\n</pre>";
   }
}

//Register Hook callbacks, added in opposite order, sorted by priority
add_action('someaction', 'callback2', 5, 4);
add_action('someaction', 'callback1', 1, 5);

//execute hook
do_action('someaction', 1234, 'foo', ['one'=>1], new stdClass, false);

输出:

callback2
<pre>#0 [...][...](25): callback2(1234, 'foo', Array, Object(stdClass))
#1 [...][...](52): do_action('someaction', 1234, 'foo', Array, Object(stdClass), false)
#2 {main}

</pre>

callback1
Array
(
    [0] => 1234
    [1] => foo
    [2] => Array
        (
            [one] => 1
        )

    [3] => stdClass Object
        (
        )
    [4] =>
)

沙盒

Stacktrace 如您在第一个输出中所看到的,我们具有应用程序的完整stacktrace(减去已编辑的信息),包括函数调用和用于这些调用的参数.还要注意,在此示例中,我将其注册为第二,但是优先级(在 add_action 中设置)使其首先执行.最后,仅使用了5个参数中的4个(也调用了 add_action 的方式).

Stacktrace As you can see in the first output, we have a complete stacktrace of the application (minus the redacted info), including the function calls and the arguments used for those calls. Also note in this example, I registered it 2nd but the priority (set in add_action) made it execute first. Lastly, only 4 of the 5 arguments were used (also do to how add_action was called).

因此 do_action 这样被调用(带有"action"和其他5个args):

So do_action was called like this (with 'action' and 5 other args):

 do_action('someaction', 1234, 'foo', Array, Object(stdClass), false)

实际的回调是这样调用的(没有'action'并且只有其他4个args):

And the actual callback was called like this (without 'action' and only 4 other args):

 callback2(1234, 'foo', Array, Object(stdClass))

功能参数这有点困难,但是它不会给您原始调用,因此您将不知道args的最大数量(您可以从args的调用中获得该数目)在堆栈跟踪中执行do_action).但是,如果您只想快速浏览一下传入的数据,那是完美的.我还要提到这一点使用了所有5个参数,您可以在数组中的第二个输出中清楚地看到这些参数. [4] => 为假,这通常是 print_r 显示假(为空)的方式.

Function Arguments This is a bit more strait forward, but it doesn't give you the original call so you won't know the maximum number of args (which you can get from the call to do_action in the stacktrace). But if you just want a quick peek at the incoming data, it's perfect. Also I should mention this one uses all 5 args, which you can clearly see in the array for the second output. The [4] => is false, this is typically how print_r displays false (as just empty).

调试Backtrace 不幸的是,出于安全原因,在沙箱中禁用了 debug_print_backtrace ,并且严重修改了Exception stacktrace(通常具有文件名和功能所在行)也出于安全原因而从调用并位于).两者都可以从连接数据库之类的操作返回参数,例如,该数据库将以纯文本格式包含DB密码.无论如何, debug_print_backtrace 与异常堆栈跟踪的外观非常接近.

Debug Backtrace Unfortunately, debug_print_backtrace is disabled (for security reasons) in the sandbox, and Exception stacktrace is heavily redacted (typically it has file names and lines where functions are called from and located at) also for security reasons. Both of these can return arguments from things like connecting to the Database, which would contain the DB password in plain text, just for example. Anyway, debug_print_backtrace is pretty close to what an exception stack trace looks like anyway.

摘要

但是无论如何,这应该使您对数据的外观有所了解.我们可以使用这样的函数(和反射)在运行时查询应用程序.我敢肯定,还有其他/更多的方法可以做类似的事情.

But in any case, this should give you an idea of what the data looks like. We can use functions like this (and Reflection) to interrogate the application at run time. I am sure there are other/more ways to do similar things too.

PS.应该不言而喻,但是无论如何我还是会说,上面的这些方法可以与任何PHP函数一起使用,并且可能非常有用.同样如上所述,您永远不要在实际生产的计算机上显示堆栈跟踪.

PS. It should go without saying, but I will say it anyway, these methods above work with any PHP function, and can be quite useful. Also as noted above, you should never show stacktraces on a live production machine.

无论如何,祝你好运.

这篇关于保存woocommerce产品后,什么是wordpress/woocommerce挂钩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆