我有一个很好的代码,可以在购买任何产品后重定向到一个定制的谢谢页面.

add_action( 'woocommerce_thankyou', 'updated_redirectcustom');
 
function updated_redirectcustom( $order_id ){
    $order = wc_get_order( $order_id );
    $url = '/thank-you/';
    if ( ! $order->has_status( 'failed' ) ) {
        wp_safe_redirect( $url );
        exit;
    }
}

我决定为几个特定的产品变体实现到另一个页面的定制重定向,但不幸的是,我更改的代码不起作用,所有订单仍然被重定向到/Thank-you/URL:

add_action( 'woocommerce_thankyou', 'updated_redirectcustom');
 
function updated_redirectcustom( $order_id ){
    $order = wc_get_order( $order_id );
    $url = '/thank-you/';
    if ( ! $order->has_status( 'failed' ) ) {
        wp_safe_redirect( $url );
        exit;
    }
    if( ! $order_id ) {
        return;
    }
    if ( is_a( $order, 'WC_Order' ) ) {
        // False
        $redirection = false;
            
        // Loop through order items
        foreach ( $order->get_items() as $item_key => $item ) {
            // Product ID(s)
            $product_ids = array( $item->get_product_id(), $item->get_variation_id() );
                    
            // Product ID in array
            if ( in_array( 12345, 123456, $product_ids ) ) {
                $redirection = true;
            }
        }
    }
    if ( $redirection ) {
        wp_safe_redirect( home_url( '/thank-you-2/' ) );
        exit;
    }
}

我哪里错了?

推荐答案

因为最后您要比较2个数组,所以使用array_intersect()来代替下面的代码行:

if ( in_array( 12345, 123456, $product_ids ) ) {

有:

if ( count( array_intersect( array(12345, 123456), $product_ids ) ) > 0 ) {

现在,它应该适用于所有产品类型,包括变种.

此外,为了缩短循环,您应该在$redirection = true;以下添加一个break;(可选).

Php相关问答推荐

产品ACF值在WooCommerce我的账户订单的附加列中为空

在Google云存储对象上从PHP设置缓存控制TTL会更改错误的元数据

在WooCommerce中禁用特定日期之前的免费送货

通过注册在Laravel中分配角色

将客户重定向到自定义感谢页后的空白页

在PHP 8.2 Gloogle云引擎上加载大型php文件速度缓慢

返回WooCommerce中的所有已启用变体

如何使用MS Graph PHP SDK V2下载文件

从两个日期创建日期范围,然后为范围中的每个日期复制子数组

HTAccess重写一些URL,但将所有其他URL发送到另一个页面

从字符串转换日期和/或时间时,Laravel转换失败

Filament PHP v3:在禁用的表单字段上,ID 不会写入数据库

致命错误:未捕获 Google_Exception:客户端机密 JSON 文件无效.在 /somepath/lib/vendor/google/apiclient/src/Google/Client.php

如何在自定义消息中包含 WooCommerce 选定的产品变体详细信息

Symfony 迁移判断器在我的工作中失控

如果有很多重定向,PHP curl 的行为不像命令行 curl

PHP / DOM : 解析 HTML 以提取基于类的数​​据

如何在 Process facade 中转义特殊字符?

无法在 Laravel 10 中安装 jenssegers/mongodb

如何将在同一台服务器上运行的 2 个 PHP 应用程序与使用公共会话分开