Категория: php

WP 1C - hook атрибутов

add_action(
    'itglx_wc1c_product_option_custom_processing_2f582177-ae22-11ec-babb-d8bbc10dcaeb',
    function (int $productId, SimpleXMLElement $property) {
        $value = html_entity_decode((string)$property->Значение);
        update_field('composition-table', $value, $productId);
    },
    10,
    2
);

Заявка в чат telegram

Как настроить отправку заявок с сайта в Telegram: пошаговое руководство




<form class="form" method="post" action="/send.php">
    <div class="form__item">
        <input class="form__input" type="text" name="name" required>
        <label class="form__label">Ваше имя</label>
    </div>
    <div class="form__item">
        <input class="form__input" type="text" name="phone" required>
        <label class="form__label">Номер телефона</label>
    </div>
    <input class="form__input btn" type="submit" value="Отправить">
    <input type="hidden" name="act" value="order">
</form>


Шаг 5: PHP-обработчик для отправки заявок в Telegram
Теперь нужно написать PHP-скрипт, который будет отправлять данные формы в Telegram-чат. Вот пример файла send.php:


<?php
// Токен, который дал @BotFather
$token = "1094153697:AAFiLXXXXXLl0hRDsxBij1lddKydKxSSsOg04";

// ID чата, в который бот будет отправлять заявки
$chat_id = "-40XXXX740";

// Проверяем, что форма была отправлена
if ($_POST['act'] == 'order') {
    // Собираем данные из формы
    $name = ($_POST['name']);
    $phone = ($_POST['phone']);

    // Формируем сообщение для отправки в Telegram
    $arr = array(
        'Имя:' => $name,
        'Телефон:' => $phone
    );

    // Собираем текст сообщения
    $txt = "";
    foreach ($arr as $key => $value) {
        $txt .= "<b>".$key."</b> ".$value."%0A";
    }

    // Отправляем запрос к API Telegram
    $sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");

    // Обрабатываем результат отправки
    if ($sendToTelegram) {
        echo 'Спасибо! Ваша заявка принята.';
    } else {
        echo 'Ошибка отправки. Попробуйте снова.';
    }
}
?>
Заключение
После выполнения всех шагов ваша форма на сайте будет отправлять заявки прямо в Telegram-чат. Теперь вы сможете оперативно получать и обрабатывать заявки, не теряя время на проверку электронной почты.

Если у вас возникнут трудности с настройкой, не стесняйтесь обращаться за помощью! Надеемся, что этот гайд был полезен для вас.

Язык WP программно

if( is_admin() )
	switch_to_locale('en_US');

Можно через хук:

add_action('init', function(){
	switch_to_locale('ru_RU');
});


больше инфы https://wp-kama.ru/function/switch_to_locale

Функция array_is_assoc($arr)

<?php
function array_is_assoc(array $arr) {
    if (array() === $arr) return false;
    return array_keys($arr) !== range(0, count($arr) - 1);
}

Функция pluck($arr, $propName)

<?php
function pluck($arr, $propName) {
    return array_map(function($item) use ($propName) {
        return is_array($item) ? $item[$propName] : $item->$propName;
    }, $arr);
}

Функция group_by($array, $key)

Объединяет элементы массива в группы.

<?php
function group_by($array, $key) {
    $result = array();
    foreach ($array as $element) {
        if(is_callable($key)) {
            $new_key = $key($element);
            $result[$new_key][] = $element;
        } else {

            $result[$element[$key]][] = $element;
        }
    }
    return $result;
}

rs_upload_from_url

Сохранение файла по ссылке в WP

<?php
function rs_upload_from_url( $url, $title = null ) {
	require_once( ABSPATH . "/wp-load.php");
	require_once( ABSPATH . "/wp-admin/includes/image.php");
	require_once( ABSPATH . "/wp-admin/includes/file.php");
	require_once( ABSPATH . "/wp-admin/includes/media.php");
	// Download url to a temp file
	$tmp = download_url( $url );
	if ( is_wp_error( $tmp ) ) return false;
	// Get the filename and extension ("photo.png" => "photo", "png")
	$filename = pathinfo($url, PATHINFO_FILENAME);
	$extension = pathinfo($url, PATHINFO_EXTENSION);
	// An extension is required or else WordPress will reject the upload
	if ( ! $extension ) {
		// Look up mime type, example: "/photo.png" -> "image/png"
		$mime = mime_content_type( $tmp );
		$mime = is_string($mime) ? sanitize_mime_type( $mime ) : false;
		// Only allow certain mime types because mime types do not always end in a valid extension (see the .doc example below)
		$mime_extensions = array(
			// mime_type         => extension (no period)
			'text/plain'         => 'txt',
			'text/csv'           => 'csv',
			'application/msword' => 'doc',
			'image/jpg'          => 'jpg',
			'image/jpeg'         => 'jpeg',
			'image/gif'          => 'gif',
			'image/png'          => 'png',
			'video/mp4'          => 'mp4',
		);
		
		if ( isset( $mime_extensions[$mime] ) ) {
			// Use the mapped extension
			$extension = $mime_extensions[$mime];
		}else{
			// Could not identify extension
			@unlink($tmp);
			return false;
		}
	}
	// Upload by "sideloading": "the same way as an uploaded file is handled by media_handle_upload"
	$args = array(
		'name' => "$filename.$extension",
		'tmp_name' => $tmp,
	);
	// Do the upload
	$attachment_id = media_handle_sideload( $args, 0, $title);
	// Cleanup temp file
	@unlink($tmp);
	// Error uploading
	if ( is_wp_error($attachment_id) ) return false;
	// Success, return attachment ID (int)
	return (int) $attachment_id;
}

Класс Query

Класс упрощает запросы для поиска записей

<?php
require $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';

class Query {

    public $query = [
        'post_type' => 'post',
        'meta_query' => [],
        'tax_query' => [],
        'posts_per_page' => -1,
        'post__not_in' => []
    ];

    function __construct($type = 'post')
    {
        $this->query['post_type'] = $type;
    }

    public function args($args = []) {
        $this->query = $args;
        return $this;
    }

    public function type($type = 'post') {
        $this->query['post_type'] = $type;
        return $this;
    }

    public function where($key, $value) {
        $this->query[$key] = $value;
        return $this;
    }

    public function meta($key, $value, $compare = '=') {
        $this->query['meta_query'][] = [
            'key' => $key,
            'value' => $value,
            'compare' => $compare
        ];
        return $this;
    }

    public function tax($tax,  $terms, $field = 'term_id') {
        $this->query['tax_query'][] = [
            'taxonomy' => $tax,
            'field' => $field,
            'terms' => $terms
        ];
        return $this;
    }

    public function count($count = -1) {
        $this->query['posts_per_page'] = $count;
        return $this;
    }

    public function postNotIn($items = []) {
        $this->query['post__not_in'] = $items;
        return $this;
    }

    public function get() {
        return get_posts($this->query);
    }

    public function wpGet() {
        return (new WP_Query($this->query));
    }

    public function metaKey($key) {
        $this->query['meta_key'] = $key;
        return $this;
    }

    public function orderBy($by, $order = 'desc') {
        $this->query['orderby'] = $by;
        $this->query['order'] = $order;
        return $this;
    }

    public function orderByMeta($by, $order = 'desc') {
        $this->orderBy('meta_value', $order);
        $this->metaKey($by);
        return $this;
    }

    public function orderByMetaNum($by, $order = 'desc') {
        $this->orderBy('meta_value_num', $order);
        $this->metaKey($by);
        return $this;
    }

    public function first() {
        $this->query['posts_per_page'] = 1;
        $posts = get_posts($this->query);
        if(!empty($posts)) {
            return $posts[0];
        }
        return null;
    }
    
    public function paged($page_number = 1) {
        $this->query['paged'] = $page_number;
        return $this;
    }
}

Класс Request

<?php
class Request
{
    private $request = [];
    private $server = [];
    private $files = [];

    public function __get($name)
    {
        return $this->get($name);
    }

    public function equals($key, $value) {
        return $this->get($key) == $value;
    }

    public function in($key, $value) {
        return in_array($value, $this->get($key));
    }

    public function __construct()
    {
        $this->request = $_REQUEST;
        $this->server = $_SERVER;
        $this->files = $_FILES;
    }
    
    public function isEmpty() {
        return empty($this->request);
    }

    public function isEmptyGet() {
        return $this->isEmpty() && $this->isGet();
    }

    public function isEmptyPost() {
        return $this->isEmpty() && $this->isPost();
    }

    public function isNotEmpty() {
        return !empty($this->request);
    }

    public function isNotEmptyPost() {
        return $this->isNotEmpty() && $this->isPost();
    }

    public function isNotEmptyGet() {
        return $this->isNotEmpty() && $this->isGet();
    }

    public function get($name, $default = null)
    {
        if ($this->has($name)) {
            return $this->request[$name];
        }
        return $default;
    }

    public function has($name)
    {
        return isset($this->request[$name]);
    }

    public function all()
    {
        return $this->request;
    }

    public function backUrl() 
    {
        return $this->server['HTTP_REFERER'];
    }

    public function method()
    {
        return $this->server['REQUEST_METHOD'];
    }

    public function isPost() {
        return $this->method() == 'POST';
    }

    public function isGet() {
        return $this->method() == 'GET';
    }

    public function ip()
    {
        if (!empty($this->server['HTTP_CLIENT_IP'])) {
            return $this->server['HTTP_CLIENT_IP'];
        } elseif (!empty($this->get['HTTP_X_FORWARED_FOR'])) {
            return $this->server['HTTP_X_FORWARED_FOR'];
        } else {
            return $this->server['REMOTE_ADDR'];
        }
    }

    public function dd()
    {
        // $dumpArray = array_merge($this->request, ['files' => $this->files]);
        echo '<pre>';
        var_dump($this->request);
        echo '</pre>';
        die;
    }

    public function header($name) {
        $name = trim(strtoupper($name));
        return $this->server["HTTP_$name"];
    }

    public function allHeaders()
    {
        return apache_request_headers();
    }

    public function files() {
        return $this->files;
    }
    

    public function file($name) {
        return $this->files[$name];
    }

    public function notEmptyFiles()
    {
        return !empty($this->files);
    }
}

XML to ARRAY

Переводит XML строки в массив

<?php
/**
* @param string $xml
*
* @return mixed
*/
function xml_to_array(string $xml): mixed
{
    $xml = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    return json_decode($json, true);
}