Категория: WordPress

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
);

Язык 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

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;
    }
}

кастомный permalink для типа записей

<?php 

add_filter(
    'pre_post_link',
    function ($permalink, $post) {
        if ($post->post_type !== 'post') {
            return $permalink;
        }

        return '/stati/%postname%/';
    },10,2);
    
    
?>

Количество записей таксономии в произвольном типе

<?php 

// Считать термины в типе данных
function get_term_post_count_by_type($term,$taxonomy,$type){
  $args = array(
    'fields' =>'ids',
    'posts_per_page' => -1,
    'post_type' => $type,
    'tax_query' => array(
      array(
        'taxonomy' => $taxonomy,
        'field' => 'slug',
        'terms' => $term
      )
    )
  );
  $ps = get_posts( $args );
  if (count($ps) > 0){
    return count($ps);
  } else {
    return 0;
  }
}



?>

Debug в файл

 <?php 
     //wp-config.php 
     
     define( 'WP_DEBUG', 0 );
     define( 'WP_DEBUG_LOG', 0);
     define( 'WP_DEBUG_DISPLAY', 0);
 ?>

Wordpress мультидомен

Позволяет привязать к одной бд/директории два и более домена (убираем привязку к домену)

<?php

// wp-config.php в самый верх

define('WP_HOME', 'https://' . $_SERVER['HTTP_HOST']);
define('WP_SITEURL', 'https://' . $_SERVER['HTTP_HOST']);
$_SERVER['HTTPS'] = 'on';
define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);

?>

Загрузка одного файла Word Press

<?php
require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php'); // Подключаем WordPress

if (!function_exists('wp_handle_upload')) // Проверяем, определена ли функция wp_handle_upload()
    require_once(ABSPATH . 'wp-admin/includes/file.php'); // Если не определена, подключаем файл для ее определения

$file = $_FILES['file']; // Получаем информацию о загруженном файле из массива $_FILES

$overrides = ['test_form' => false]; // Определяем опции для обработки файла в функции wp_handle_upload()

$movefile = wp_handle_upload($file, $overrides); // Обрабатываем загруженный файл и получаем информацию о перемещенном файле или сообщение об ошибке

if ($movefile && empty($movefile['error'])) { // Проверяем, успешно ли был обработан загруженный файл
    $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename($movefile['file']), // Полный URL файла, включая имя файла
        'post_mime_type' => $movefile['type'], // MIME-тип файла
        'post_title'     => preg_replace('/\.[^.]+$/', '', basename($movefile['file'])), // Имя файла без расширения
        'post_content'   => '', // Описание файла
        'post_status'    => 'publish' // Статус публикации вложения (опубликовано)
    );
    $attach_id = wp_insert_attachment($attachment, $movefile['file']); // Добавляем вложение в медиабиблиотеку WordPress и сохраняем его ID в $attach_id
}

Загрузка нескольких файлов WordPress

<?php
require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
if (!function_exists('wp_handle_upload'))
        require_once(ABSPATH . 'wp-admin/includes/file.php');

    $files = $_FILES['files'];
    $overrides = ['test_form' => false];
    foreach ($files['name'] as $key => $value) {
        if ($files['name'][$key]) {
            $file = array(
                'name'     => $files['name'][$key],
                'type'     => $files['type'][$key],
                'tmp_name' => $files['tmp_name'][$key],
                'error'    => $files['error'][$key],
                'size'     => $files['size'][$key]
            );
            $movefile = wp_handle_upload($file, $overrides);
            if ($movefile && empty($movefile['error'])) {
                $attachment = array(
                    'guid'           => $wp_upload_dir['url'] . '/' . basename($movefile['file']),
                    'post_mime_type' => $movefile['type'],
                    'post_title'     => preg_replace('/\.[^.]+$/', '', basename($movefile['file'])),
                    'post_content'   => '',
                    'post_status'    => 'publish'
                );
                $attach_ids[] = wp_insert_attachment($attachment, $movefile['file']);
            }
        }
    }