Skip to content

Commit

Permalink
Настройки вынесены в отдельный класс
Browse files Browse the repository at this point in the history
  • Loading branch information
ivannin committed Apr 25, 2022
1 parent 24f6568 commit 343b090
Show file tree
Hide file tree
Showing 4 changed files with 127 additions and 96 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
cid2order -- сохранение ClientID в заказах Woocommerce и формах ContactForm 7
==============================================================================

cid2order - плагин для Woocommerce, который сохраняет ClientID Google Analytics, Яндекс.Метрика и других счетчиков в полях заказа.
==================================================================================================================================
Также плагин может сохранять ClientIds в формах ContactForm 7.

Версия 0.1
Версия 0.2

Задача, решаемая плагином
-------------------------

При отладке и проверке аналитических систем на сайте, а также для ряда других случаев требуется знать Client IDs (CID) пользователя,
который совершил заказ. Как правило CID назначается трекерами аналитических систем (Google Analytics, Яндекс.метрика) и сохраняется
который совершил заказ. Как правило CID назначается трекерами аналитических систем (Google Analytics, Яндекс.Метрика) и сохраняется
в куки пользователя.

Этот плагин в момент совершения заказа считывает куки трекеров по указанному в настройках списку и сохраняет их значения
Expand Down
9 changes: 5 additions & 4 deletions cid2order.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?php
/**
* cid2order
* cid2order
*
* @package in-qr-payment
* @package cid2order
* @author Ivan Nikitin
* @copyright 2021 IvanNikitin.com
* @license GPL-2.0-or-later
*
* @wordpress-plugin
* Plugin Name: cid2order
* Plugin URI: https://github.com/ivannikitin-com/cid2order
* Description: Плагин для Woocommerce, который сохраняет ClientID Google Analytics, Яндекс.Метрика и других счетчиков в полях заказа.
* Version: 0.1
* Description: Плагин для Woocommerce, который сохраняет ClientID Google Analytics, Яндекс.Метрика и других счетчиков в полях заказа и в формах ContactForm 7.
* Version: 0.2
* Requires at least: 5.9
* Requires PHP: 7.4
* Author: Иван Никитин
Expand All @@ -31,6 +31,7 @@

/* Файлы ядра плагина */
require_once( 'classes/plugin.php' );
require_once( 'classes/settings.php' );

/**
* Запуск плагина
Expand Down
148 changes: 59 additions & 89 deletions classes/plugin.php
Original file line number Diff line number Diff line change
@@ -1,103 +1,76 @@
<?php
/**
* Класс Cid2order_plugin
* Основной класс плагина.
* Является singleton, то есть обращение из любого места должно быть таким Plugin::get()
* Основной класс плагина.
*/
class Cid2order_plugin {

/**
* @var mixed
* @var mixed
* Параметры плагина в виде ассоциативного массива
*/
public $settings;
*/
private $settings;

/**
* Параметры по умолчанию
* Используем статичную переменную, так как константы класса не могут быть массивом
*/
public static $DEFAULTS = array(
'cookies' => array( '_ga', '_ym_uid' ),
'save' => array(
'order_notes' => true
)
);

/**
* Конструктор плагина
* Конструктор плагина
*/
public function __construct()
{
// Хуки
add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ) );
add_action( 'init', array( $this, 'wp_init' ) );
add_action( 'woocommerce_thankyou', array( $this, 'thankyou_page' ) );
public function __construct() {
// Настройки плагина
$this->settings = new Cid2order_settings();

// Хуки
add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ) );
add_action( 'init', array( $this, 'wp_init' ) );
add_action( 'woocommerce_thankyou', array( $this, 'thankyou_page' ) );
add_filter( 'manage_edit-shop_order_columns', array( $this, 'custom_shop_order_column' ), 20 );
add_action( 'manage_shop_order_posts_custom_column', array( $this, 'custom_orders_list_column_content' ), 20, 2 );
}

/**
* Плагины загружены
*/
public function plugins_loaded()
{
// Локализация
load_plugin_textdomain( CID2ORDER, false, CID2ORDER_DIR . '/lang' );
}

/**
* Хук init
*/
public function wp_init()
{
// Проверка наличия WC
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) )
{
add_action( 'admin_notices', array( $this, 'show_notice_no_wc' ) );
return;
}

// загрузка параметров плагина
$this->load_settings( self::$DEFAULTS );
}

/**
* Предупреждение об отсутствии WooCommerce
*/
public function show_notice_no_wc()
{
echo '<div class="notice notice-warning no-woocommerce"><p>';
printf(
esc_html__( 'Для работы плагина "%s" требуется установить и активировать плагин WooCommerce.', CID2ORDER ),
CID2ORDER
);
_e( 'В настоящий момент все функции плагина деактивированы.', CID2ORDER );
echo '</p></div>';
}

/**
* Загрузка параметров плагина
* @param mixed $defaults Параметры по умолчанию
*/
public function load_settings( $defaults )
{
// TODO: Сделать страницу параметров
$this->settings = $defaults;
}

/**
* Функция выполняется на странице Thank you page WooCommerce
* @param int $order_id Идентификатор заказа
* Плагины загружены
*/
public function plugins_loaded() {
// Локализация
load_plugin_textdomain( CID2ORDER, false, CID2ORDER_DIR . '/lang' );
}

/**
* Хук init
*/
public function wp_init() {
// Проверка наличия WC
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) )
{
add_action( 'admin_notices', array( $this, 'show_notice_no_wc' ) );
return;
}
}

/**
* Предупреждение об отсутствии WooCommerce
*/
public function show_notice_no_wc() {
echo '<div class="notice notice-warning no-woocommerce"><p>';
printf(
esc_html__( 'Для работы плагина "%s" требуется установить и активировать плагин WooCommerce.', CID2ORDER ),
CID2ORDER
);
_e( 'В настоящий момент все функции плагина деактивированы.', CID2ORDER );
echo '</p></div>';
}

/**
* Функция выполняется на странице Thank you page WooCommerce
* @param int $order_id Идентификатор заказа
*/
public function thankyou_page( $order_id )
{
public function thankyou_page( $order_id ) {
// Если по какой-то причине $order_id нет, ничего не делаем
if ( empty( $order_id ) ) return;

$cid_str = '';

// Читаем требуемые куки
foreach ($this->settings[ 'cookies' ] as $cookie) {
foreach ($this->settings->get( 'cookies' ) as $cookie) {
// Если текущего куки нет, переходим к следующему
if ( !isset( $_COOKIE[ $cookie ] ) || empty( $_COOKIE[ $cookie ] ) ) continue;

Expand All @@ -109,18 +82,17 @@ public function thankyou_page( $order_id )
}

// При необходимости сохраняем данные в заметку к заказу
if ( $this->settings[ 'save' ][ 'order_notes' ] && !empty( $cid_str ) ) {
if ( $this->settings->get( 'save' )[ 'order_notes' ] && !empty( $cid_str ) ) {
$order = new WC_Order( $order_id );
$order->add_order_note( __('Client IDs', CID2ORDER ) . $cid_str );
}
}

/**
* Функция Добавляет новую колонку в список заказов
* @param mixed $columns Массив колонок
* Функция Добавляет новую колонку в список заказов
* @param mixed $columns Массив колонок
*/
public function custom_shop_order_column( $columns )
{
public function custom_shop_order_column( $columns ) {
$new_columns = array();

// Добавляем колонку ПОСЛЕ order_total
Expand All @@ -135,18 +107,17 @@ public function custom_shop_order_column( $columns )
}

/**
* Функция выводит данные в новую колонку в списке заказов
* @param string $column ID колонки
* @param int $post_id ID заказа
* Функция выводит данные в новую колонку в списке заказов
* @param string $column ID колонки
* @param int $post_id ID заказа
*/
function custom_orders_list_column_content( $column, $post_id )
{
function custom_orders_list_column_content( $column, $post_id ) {
if ( 'cid' == $column) {

$column_values = array();

// Читаем требуемые поля -- названия куки
foreach ( $this->settings[ 'cookies' ] as $cookie ) {
foreach ( $this->settings->get( 'cookies' ) as $cookie ) {
$value = get_post_meta( $post_id, $cookie, true );
if ( ! empty( $value ) ) {
$column_values[] = $cookie . ': ' . $value;
Expand All @@ -157,7 +128,6 @@ function custom_orders_list_column_content( $column, $post_id )
if ( count( $column_values ) > 0 ) {
echo implode( '<br>', $column_values );
}

}
}
}
57 changes: 57 additions & 0 deletions classes/settings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
/**
* Класс Cid2order_settings
* Обеспечивает чтение и сохранение настроек плагина.
*/
class Cid2order_settings {
/**
* Параметры по умолчанию
* Используем статичную переменную, так как константы класса не могут быть массивом
*/
private static $DEFAULTS = array(
'cookies' => array( '_ga', '_ym_uid' ),
'save' => array(
'order_notes' => true
)
);

/**
* @var mixed
* Параметры плагина в виде ассоциативного массива
*/
private $settings;

/**
* Конструктор класса, инициализация
*/
public function __construct() {
// Инициализация массива настроек
$this->settings = array();
}

/**
* Чтение параметра настроек
* @param string $param Имя параметра
* @return mixed Возвращает значение параметра или null
*/
public function get( $param ) {
// Если массив настроек пустой, значит нужно загрузить настройки
if ( 0 == count( $this->settings ) ) $this->load_settings( self::$DEFAULTS );

// Проверяем наличие параметра
if ( !array_key_exists( $param, $this->settings ) ) return null;

// Возвращает параметр
return $this->settings[ $param ];
}

/**
* Загрузка параметров плагина
* @param mixed $defaults Параметры по умолчанию
*/
private function load_settings( $defaults ) {
$this->settings = $defaults;
}


}

0 comments on commit 343b090

Please sign in to comment.