WordPress/WooCommerce:保存自定义付款 post 元

WordPress/WooCommerce: Save custom payment post meta

我正在使用创建自定义支付类型的插件,用户可以在其中填写自定义支付 ID。问题是,我希望将自定义支付 ID 作为 WooCommerce 订单编辑页面上的 post 元存储在 ACF 字段中。我为此任务创建了一个名为 'kkpayment' 的 ACF 字段。我想剩下的应该使用 update_field($selector, $value, [$post_id]); 来完成。我为此任务创建了一个 PHP 函数。但是,我的代码似乎不起作用。我是否遗漏了一些明显的东西?

我更新 ACF 字段的函数:

add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta_acf' );
function custom_payment_update_order_meta_acf( $order_id ) {
$transaction = get_post_meta( $order->id, 'transaction', true );

    if($_POST['payment_method'] = 'custom')
        return $transaction;

    update_field('kkpayment', $transaction, $order_id);
    
}

使用此代码进行自定义付款:

<?php
/*
Plugin Name: KK Payment Gateway
Description: Modtag betaling med kontostreng
Author: Arvin Aliari & Tobias Hyrup
Author URI: https://aliari.dk
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

/**
 * Baseret på StackOverlow: 
 *
 * Tilpasninger til dette projekt, se linje 135 - 161
 *
 *
 *
 * Custom Payment Gateway.
 *
 * Provides a Custom Payment Gateway.
 */
add_action('plugins_loaded', 'init_custom_gateway_class');

function init_custom_gateway_class(){

    class WC_Gateway_Custom extends WC_Payment_Gateway {

        public $domain;

        /**
         * Constructor for the gateway.e Number
         */
        public function __construct() {

            $this->domain = 'custom_payment';

            $this->id                 = 'custom';
            $this->icon               = apply_filters('woocommerce_custom_gateway_icon', '');
            $this->has_fields         = false;
            $this->method_title       = __( 'Prisme', $this->domain );
            $this->method_description = __( 'Tag i mod betaling fra Prisme.', $this->domain );

            // Load the settings.
            $this->init_form_fields();
            $this->init_settings();

            // Define user set variables
            $this->title        = $this->get_option( 'title' );
            $this->description  = $this->get_option( 'description' );
            $this->instructions = $this->get_option( 'instructions', $this->description );
            $this->order_status = $this->get_option( 'order_status', 'completed' );

            // Actions
            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
            add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );

            // Customer Emails
            add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
        }

        /**
         * Initialise Gateway Settings Form Fields.
         */
        public function init_form_fields() {

            $this->form_fields = array(
                'enabled' => array(
                    'title'   => __( 'Aktiver/Deaktiver', $this->domain ),
                    'type'    => 'checkbox',
                    'label'   => __( 'Tillad betaling med kontostreng', $this->domain ),
                    'default' => 'yes'
                ),
                'title' => array(
                    'title'       => __( 'Titel', $this->domain ),
                    'type'        => 'text',
                    'description' => __( 'Angiver den titel som brugeren ser under checkout.', $this->domain ),
                    'default'     => __( 'Betaling med kontostreng', $this->domain ),
                    'desc_tip'    => true,
                ),
                'order_status' => array(
                    'title'       => __( 'Ordrestatus', $this->domain ),
                    'type'        => 'select',
                    'class'       => 'wc-enhanced-select',
                    'description' => __( 'Vælg hvilken status du ønsker efter chekout.', $this->domain ),
                    'default'     => 'wc-completed',
                    'desc_tip'    => true,
                    'options'     => wc_get_order_statuses()
                ),
                'description' => array(
                    'title'       => __( 'Beskrivelse', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Beskrivelse af betalingsmetoden som brugerene ser under chekout.', $this->domain ),
                    'default'     => __('Payment Information', $this->domain),
                    'desc_tip'    => true,
                ),
                'instructions' => array(
                    'title'       => __( 'Instruktioner', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Besked som brugerene vil se på efter gennemført ordre.', $this->domain ),
                    'default'     => '',
                    'desc_tip'    => true,
                ),
            );
        }

        /**
         * Output for the order received page.
         */
        public function thankyou_page() {
            if ( $this->instructions )
                echo wpautop( wptexturize( $this->instructions ) );
        }

        /**
         * Add content to the WC emails.
         *
         * @access public
         * @param WC_Order $order
         * @param bool $sent_to_admin
         * @param bool $plain_text
         */
        public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
            if ( $this->instructions && ! $sent_to_admin && 'custom' === $order->payment_method && $order->has_status( 'on-hold' ) ) {
                echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
            }
        }

        public function payment_fields(){

            if ( $description = $this->get_description() ) {
                echo wpautop( wptexturize( $description ) );
            }

            ?>
            <div id="custom_input">
              <p class="form-row form-row-wide">
                    <label for="transaction" class=""><?php _e('26-cifret kontostreng:', $this->domain); ?></label>
                    <input type="text" class="" name="transaction" id="transaction" placeholder="12345-1234-123-123456789-123-12" value="" style="width: 225px;">
                </p>
                <p style="opacity: 0.75; margin-top:-10px; font-size: 13.5px;">Eks: 12345-1234-123-123456789-123-12</p>
                <p>Hvis du ikke har en kontostreng, så kontakt din nærmeste leder eller økonomimedarbejder.</p>
            </div>
            <?php
        }


        public function validate_fields(){

            $paymentString = $_POST['transaction'];
            $strLength = strlen($paymentString);

            /*$stringContains = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{7}[-]\d{3}[-]\d{2}$/", $paymentString);*/

            $stringContains = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{9}[-]\d{3}[-]\d{2}$/", $paymentString);
            if($stringContains && !empty($_POST['transaction']) && $_POST['transaction'] != "") {
                return true;
            } else  {
                $stringOldPattern = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{7}[-]\d{3}[-]\d{2}$/", $paymentString);
                if($stringOldPattern){
                    wc_add_notice(  "Ugyldig kontostreng - Husk at bruge det nye format på 26 cifre der inkluderer funktionskode. Tjek at du har indtastet kontostrengen korrekt. Eksempel: 12345-1234-123-123456789-123-12", 'error' );
                } else  {
                    wc_add_notice(  "Ugyldig kontostreng - Tjek at du har indtastet kontostrengen korrekt. Eksempel: 12345-1234-123-123456789-123-12", 'error' );
                }
                return false;
            }
        }


        /**
         * Process the payment and return the result.
         *
         * @param int $order_id
         * @return array
         */
        public function process_payment( $order_id ) {

            $order = wc_get_order( $order_id );

            $status = 'wc-' === substr( $this->order_status, 0, 3 ) ? substr( $this->order_status, 3 ) : $this->order_status;

            // Set order status
            $order->update_status( $status, __( 'Checkout with custom payment. ', $this->domain ) );

            // Reduce stock levels
            $order->reduce_order_stock();

            // Remove cart
            WC()->cart->empty_cart();

            // Return thankyou redirect
            return array(
                'result'    => 'success',
                'redirect'  => $this->get_return_url( $order )
            );
        }
    }
}

add_filter( 'woocommerce_payment_gateways', 'add_custom_gateway_class' );
function add_custom_gateway_class( $methods ) {
    $methods[] = 'WC_Gateway_Custom';
    return $methods;
}

add_action('woocommerce_checkout_process', 'process_custom_payment');
function process_custom_payment(){

    if($_POST['payment_method'] != 'custom')
        return;


    if( !isset($_POST['transaction']) || empty($_POST['transaction']) )
        //wc_add_notice( __( 'Angiv venligst dit 26-cifret kontostreng til Prisme', $this->domain ), 'error' );
        wc_add_notice( __( 'Angiv venligst dit 26-cifret kontostreng til Prisme', ), 'error' );

}

/**
 * Update the order meta with field value
 */
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta' );
function custom_payment_update_order_meta( $order_id ) {

    if($_POST['payment_method'] != 'custom')
        return;

    // echo "<pre>";
    // print_r($_POST);
    // echo "</pre>";
    // exit();

    
    update_post_meta( $order_id, 'transaction', $_POST['transaction'] );
}

/**
 * Display field value on the order edit page
 */
add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_checkout_field_display_admin_order_meta', 10, 1 );
function custom_checkout_field_display_admin_order_meta($order){
    $method = get_post_meta( $order->id, '_payment_method', true );
    if($method != 'custom')
        return;

    $transaction = get_post_meta( $order->id, 'transaction', true );

    echo '<p><strong>'.__( '26 cifret kontostreng').':</strong> ' . $transaction . '</p>';
}



/**
 * Add payment to metadata
 */
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta_acf' );
function custom_payment_update_order_meta_acf( $order_id ) {
$transaction = get_post_meta( $order->id, 'transaction', true );

    if($_POST['payment_method'] = 'custom')
        return $transaction;

    update_field('kkpayment', $transaction, $order_id);
    
}

使用此代码在交易成功时更新 acf 字段。

add_action( 'woocommerce_thankyou', 'bks_post_transaction_after_order_completion', 10, 1 );

function bks_post_transaction_after_order_completion( $order_id ) {
$order = wc_get_order( $order_id ); // phpcs:ignore.
$status = $order->get_status();

// Try to post only when order status is completed or processing.
if ( ! ( 'completed' === $status || 'processing' === $status ) ) {
return;
}

// get transaction.
$transaction = get_post_meta( $order->id, 'transaction', true );

update_field('kkpayment', $transaction, $order_id);
$order->update_meta_data( 'kkpayment', $transaction ); // phpcs:ignore
$order->save();
}