Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[MarketPress] - Checkout Custom Fields
<?php
/*
Plugin Name: [MarketPress] - Checkout Custom Fields
Plugin URI: https://premium.wpmudev.org/
Description: Inserts custom fields in checkout page
Author: Panos Lyrakis @ WPMUDEV
Author URI: https://premium.wpmudev.org/
License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WPMUDEV_MP_Checkout_Custom_Fields' ) ) {
class WPMUDEV_MP_Checkout_Custom_Fields {
private static $_instance = null;
private $_custom_fields = array();
private $_remove_fields = array();
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_MP_Checkout_Custom_Fields();
}
return self::$_instance;
}
public function __construct() {
add_filter( 'mp_checkout/address_fields_array', array( $this, 'handle_fields' ), 20, 2 );
add_filter( 'mp_order/get_address', array( $this, 'get_address' ), 20, 3 );
}
public function get_custom_fields( $type = 'billing' ){
$custom_fields = array();
if( 'billing' == $type ){
$custom_fields['custom_field_one'] = array(
'type' => 'text',
'label' => __( 'Custom field one', 'mp' ),
'name' => $this->field_name( 'custom_field_one', $type ),
'value' => mp_get_user_address_part( 'custom_field_one', $type ),
'atts' => array(
'class' => 'mp_form_input',
),
);
$custom_fields['custom_field_two'] = array(
'type' => 'text',
'label' => __( 'Custom field two', 'mp' ),
'name' => $this->field_name( 'custom_field_two', $type ),
'value' => mp_get_user_address_part( 'custom_field_two', $type ),
'atts' => array(
'class' => 'mp_form_input',
),
);
}
return $custom_fields;
}
public function get_address( $html, $type, $order ) {
$custom_fields = $this->get_custom_fields();
if( ! empty( $custom_fields ) ) {
foreach( $custom_fields as $key => $custom_field ) {
$field_label = $custom_field['label'];
$field_value = $order->get_meta( "mp_{$type}_info->{$key}" );
$html .= "<div><strong>{$field_label}</strong>: {$field_value}</div>";
}
}
return $html;
}
public function handle_fields( $address_fields, $type ) {
$custom_fields = $this->get_custom_fields( $type );
if( is_array( $custom_fields ) && ! empty( $custom_fields ) ){
foreach( $custom_fields as $key => $custom_field ) {
$address_fields[] = $custom_field;
}
}
return $address_fields;
}
public function field_name( $name, $prefix = null ) {
if ( !is_null( $prefix ) ) {
return $prefix . '[' . $name . ']';
}
return $name;
}
}
add_action( 'plugins_loaded', function(){
$GLOBALS['WPMUDEV_MP_Checkout_Custom_Fields'] = WPMUDEV_MP_Checkout_Custom_Fields::get_instance();
}, 20 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.