# REGISTER ORDER POST TYPE
function post_type_order() {
$labels = array(
'name' => _x( 'Orders', 'post type general name' ),
'singular_name' => _x( 'Order', 'post type singular name' ),
'add_new' => _x( 'Add New', 'order' ),
'add_new_item' => __( 'Add New Order' ),
'edit_item' => __( 'Edit Order' ),
'new_item' => __( 'New Order' ),
'all_items' => __( 'All Orders' ),
'view_item' => __( 'View Order' ),
'search_items' => __( 'Search Orders' ),
'not_found' => __( 'No order found' ),
'not_found_in_trash' => __( 'No orders found in the Trash' ),
'menu_name' => 'Orders'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our orders and order specific data',
'public' => true,
'menu_icon' => 'dashicons-cart',
'menu_position' => 1,
'supports' => array( 'title', 'custom-fields' ),
'has_archive' => true,
);
register_post_type( 'ordersss', $args );
}
add_action( 'init', 'post_type_order' );
<?php
// Silence is golden.
'post_name'=>'test',
) на наличие / существование страницы$page=get_page_by_path('test',OBJECT,'page');
$post_new = array(
'post_title' => 'Заголовок',
'post_name' => 'test',
'post_content' => 'Здесь должен быть контент',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
);
if(!$page){
$post_id=wp_insert_post(wp_slash($post_new));
}
add_shortcode( 'gorod', 'gorod_func' );
$gorod = 'Тюмень';
function gorod_func( $atts ){
return $GLOBALS['gorod'];
}
add_shortcode( 'gorod', 'gorod_func' );
$gorod = 'Тюмень';
function gorod_func( $atts ){
global $gorod;
return $gorod;
}
function spShtcode_function($atts)
{...
$out='';
$out .=
$out .=
...
return $out;
}
function spShtcode_function($atts)
{
ob_start();
...
//все через echo или через HTML: ?>аля ля<?php
echo '<div class="uk-padding-small">';
...
if($cform=get_field('forma')) {
echo $cform;
}
...
return ob_get_clean();
}
Подсмотрел в гайд, вот здесь, здесь есть образец создания класса-контрола в самом начале, но простого нотиса, который ничего не позволяет менять
<?php
if(!defined('ABSPATH')){exit;}
class Skyrocket_TinyMCE_Custom_control extends WP_Customize_Control{
/**
* The type of control being rendered
*/
public $type = 'tinymce_editor';
/**
* Enqueue our scripts and styles
*/
public function enqueue(){
wp_enqueue_script( 'skyrocket-custom-controls-js', get_template_directory_uri() . '/js/customizer.js', array( 'jquery' ), '1.0', true );
wp_enqueue_style( 'skyrocket-custom-controls-css', get_template_directory_uri() . '/css/customizer.css', array(), '1.0', 'all' );
wp_enqueue_editor();
}
/**
* Pass our TinyMCE toolbar string to JavaScript
*/
public function to_json() {
parent::to_json();
$this->json['skyrockettinymcetoolbar1'] = isset( $this->input_attrs['toolbar1'] ) ? esc_attr( $this->input_attrs['toolbar1'] ) : 'bold italic bullist numlist alignleft aligncenter alignright link';
$this->json['skyrockettinymcetoolbar2'] = isset( $this->input_attrs['toolbar2'] ) ? esc_attr( $this->input_attrs['toolbar2'] ) : '';
$this->json['skyrocketmediabuttons'] = isset( $this->input_attrs['mediaButtons'] ) && ( $this->input_attrs['mediaButtons'] === true ) ? true : false;
}
/**
* Render the control in the customizer
*/
public function render_content(){
?>
<div class="tinymce-control">
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<?php if( !empty( $this->description ) ) { ?>
<span class="customize-control-description"><?php echo esc_html( $this->description ); ?></span>
<?php } ?>
<textarea id="<?php echo esc_attr( $this->id ); ?>" class="customize-control-tinymce-editor" <?php $this->link(); ?>><?php echo esc_attr( $this->value() ); ?></textarea>
</div>
<?php
}
}
/* ==========================================================================
Textarea/TinyMCE
========================================================================== */
.tinymce-control textarea {
width: 100%;
padding: 10px;
}
jQuery( document ).ready(function($) {
"use strict";
/**
* TinyMCE Custom Control
*
* @author Anthony Hortin <http://maddisondesigns.com>
* @license http://www.gnu.org/licenses/gpl-2.0.html
* @link https://github.com/maddisondesigns
*/
$('.customize-control-tinymce-editor').each(function(){
// Get the toolbar strings that were passed from the PHP Class
var tinyMCEToolbar1String = _wpCustomizeSettings.controls[$(this).attr('id')].skyrockettinymcetoolbar1;
var tinyMCEToolbar2String = _wpCustomizeSettings.controls[$(this).attr('id')].skyrockettinymcetoolbar2;
var tinyMCEMediaButtons = _wpCustomizeSettings.controls[$(this).attr('id')].skyrocketmediabuttons;
wp.editor.initialize( $(this).attr('id'), {
tinymce: {
wpautop: true,
toolbar1: tinyMCEToolbar1String,
toolbar2: tinyMCEToolbar2String
},
quicktags: true,
mediaButtons: tinyMCEMediaButtons
});
});
$(document).on( 'tinymce-editor-init', function( event, editor ) {
editor.on('change', function(e) {
tinyMCE.triggerSave();
$('#'+editor.id).trigger('change');
});
});
});
...
$customizer->add_setting( 'sample_tinymce_editor',
array(
'default' => '',
// 'transport' => 'postMessage',
'sanitize_callback' => 'wp_kses_post'
)
);
$customizer->add_control( new Skyrocket_TinyMCE_Custom_control( $customizer, 'sample_tinymce_editor',
array(
'label' => __( 'TinyMCE Control' ),
'description' => __( 'This is a TinyMCE Editor Custom Control' ),
'section' => 'section_VAB_Agree',
'input_attrs' => array(
'toolbar1' => 'bold italic bullist numlist alignleft aligncenter alignright link',
'mediaButtons' => true,
)
)
));
...
echo get_theme_mod('sample_tinymce_editor');
add_action('admin_init','wpse_57647_register_settings');
function wpse_57647_register_settings(){
register_setting(
'general',
'html_guidelines_message',
'textarea' // <--- Customize this if there are multiple fields
);
add_settings_section(
'site-guide',
'Publishing Guidelines',
'__return_false',
'general'
);
add_settings_field(
'html_guidelines_message',
'Enter custom message',
'wpse_57647_print_text_editor',
'general',
'site-guide'
);
}
/*
* Print settings field content
*/
function wpse_57647_print_text_editor(){
$the_guides=!empty(get_option('html_guidelines_message'))?html_entity_decode(get_option('html_guidelines_message')):'';
echo '<textarea cols="44" placeholder="'.__('Поле для ввода текста','VAB').'"name="html_guidelines_message" id="html_guidelines_message" value="">'.$the_guides.'</textarea>';
}
function add_option_field_to_general_admin_page(){
$option_name='my_option';
// регистрируем опцию
register_setting('general',$option_name);
// добавляем поле
add_settings_field(
'myprefix_setting-id',
'Название опции',
'myprefix_setting_callback_function',
'general',
'default',
array(
'id'=>'myprefix_setting-id',
'option_name'=>'my_option'
)
);
}
add_action('admin_menu','add_option_field_to_general_admin_page');
function myprefix_setting_callback_function($val){
$id=$val['id'];
$option_name=$val['option_name'];
$the_guides=!empty(get_option($option_name))?html_entity_decode(get_option($option_name)):'';
echo '<textarea cols="44" placeholder="'.__('Поле для ввода текста','VAB').'"name="'.$option_name.'" id="'.$option_name.'" value="">'.$the_guides.'</textarea>';
}
В чём может быть проблема?
Но проблема в том, что модальное окно показывается постоянно при попытке закрыть страницу. При этом сами куки устанавливаются.
...
var alertwin = getCookie("alertwin");//при отсутствии куки тут пусто.
//значение легло при загрузке страницы
//значит после установки куки надо перезагрузить страницу, чтоб там что-то было
//либо сделать повторный запрос getCookie(name)
if (alertwin != "no") {
$(document).mouseleave(function(e){
if (e.clientY < 0) {
...
_________________________________________________________________________
...
$(document).mouseleave(function(e){
var alertwin = getCookie("alertwin");//получаем куку при каждом событии mouseleave
//при первом событии там пусто и код ниже отработает
//при повторном наведении там не пусто и код ниже не отработает
if (alertwin != "no") {
...
А в поле кастомайзера хочу через запятую выводить нужные артикулы
...
$skus = get_theme_mod('skus');
$skus = explode(',',$skus);
...
$pizza = "кусок1 кусок2 кусок3 кусок4 кусок5 кусок6";
$pieces = explode(" ", $pizza);
...
$skus = get_theme_mod('skus');
$skus = explode(',',$skus);
...
'value' => $skus,
...
if ( isset( $_REQUEST['action'] ) && 'add-site' === $_REQUEST['action'] ) {
check_admin_referer
// 1
add_action('check_admin_referer',function($action){
$blog_count=get_blog_count();
if(is_network_admin()&&isset($_REQUEST['action'])&&'add-site'===$_REQUEST['action']&&$blog_count==2){
wp_die(__('Достигнут лимит','VAB'));
}});
// 2
$blog_count=get_blog_count();
if(is_network_admin()&&isset($_REQUEST['action'])&&'add-site'===$_REQUEST['action']&&$blog_count==2){
add_action('check_admin_referer',function($action){
// if('add-blog'!==$action){return;}
wp_die(__('Достигнут лимит','VAB'));
});}
// ... другие аналоги
do_action( 'network_site_new_form' );
перед выводом в разметке кнопки для создания и далее подключаются стили и скрипты. Можно воспользоваться add_action('network_site_new_form'
и остановить все, что послеrequire_once ABSPATH . 'wp-admin/admin-footer.php';
add_action('network_site_new_form','action_function_name_6729');
function action_function_name_6729(){
$blog_count=get_blog_count();
if($blog_count==2){exit();}
}
add_action("admin_print_scripts-site-new.php",'my_admin_scripts');
function my_admin_scripts(){
$blog_count=get_blog_count();
if($blog_count==2){
exit('<center><strong style="font-size:33px;">'.__('Достигнут лимит создания поддоменов','VAB').'</strong></center>');}}
Как будет правильно?
... не работает, почему?
function my_post_comment_meta_box( $comment ) {
$total=get_comments(
array(
'post_id' => $comment->comment_post_ID,
)
);
foreach($total as $mass){
var_dump($mass);
echo '<a href="'.get_site_url().'/wp-admin/comment.php?action=editcomment&c='.$mass->comment_ID.'">'.esc_html__('Редактировать','VAB').'</a>';
echo'<br><br>Отступ м/у комментариями<br><br>';
}
}
$total=get_comments(array('post_id'=>$comment->comment_post_ID,));
Где-то же это значение указано? Где копать?
add_action( 'wp_initialize_site', 'wpdocs_action_wp_initialize_site', 900 );
/**
* Fires when a site's initialization routine should be executed.
*
* @param WP_Site $new_site New site object.
*/
function wpdocs_action_wp_initialize_site( WP_Site $new_site ) : void {
switch_to_blog( $new_site->blog_id );
update_option('gmt_offset','1');
//update_option('gmt_offset','1.5');
//update_option('gmt_offset','2');
//update_option('gmt_offset','2.5');
//update_option('gmt_offset','3'); //установлено по умолчанию
restore_current_blog();
}
function update_basic_user_meta(){
global $current_user;
$communication_meta=!empty($_POST['communication_email'])?$_POST['communication_email']:'';
if(!empty($communication_meta)){update_user_meta($current_user->ID,'communication_email',sanitize_text_field($communication_meta));}
$communication_email=get_user_meta($current_user->ID,'communication_email',true);?>
<form action="" method="POST" class="">
<input type="text" id="communicationEmail" name="communication_email" class="" value="<?php echo !empty($communication_email)?$communication_email:''; ?>">
<button class="" type="submit">Сохранять</button>
</form><?php }
update_basic_user_meta();
Вопрос - как?
... этот цвет применить еще к некоторым дивам в этой теме?
add_action('wp_head','div_style');
if(!function_exists('div_style')){function div_style(){?>
<style id="div_style" type="text/css">
.div_style{background-color:#<?php echo get_theme_mod('background_color');?>;}
</style>
<?php }}
...............или...............
add_action('get_footer','div_style');
if(!function_exists('div_style')){function div_style(){?>
<style id="div_style" type="text/css">
.div_style{background-color:#<?php echo get_theme_mod('background_color');?>;}
</style>
<?php }}
...
global $phpmailer;
// (Re)create it, if it's gone missing. - (Повторно) создайте его, если он пропал
if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer ) ) {
require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
$phpmailer = new PHPMailer\PHPMailer\PHPMailer( true );
$phpmailer::$validator = static function ( $email ) {
return (bool) is_email( $email );
};
}
...
global $phpmailer; //не помогло
//слизал подключение из wp_mail и отправилось
// (Re)create it, if it's gone missing.
if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer ) ) {
require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php';
require_once ABSPATH . WPINC . '/PHPMailer/Exception.php';
$phpmailer = new PHPMailer\PHPMailer\PHPMailer( true );
$phpmailer::$validator = static function ( $email ) {
return (bool) is_email( $email );
};
}
// Создаем письмо
$mail = $phpmailer;
$mail->isSMTP(); // Отправка через SMTP
$mail->Host = 'smtp.yandex.ru'; // Адрес SMTP сервера
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'login'; // ваше имя пользователя
$mail->Password = 'password'; // ваш пароль
$mail->SMTPSecure = 'ssl'; // шифрование ssl
$mail->Port = 465; // порт подключения
$mail->setFrom('login@ya.ru', 'Иван Иванов'); // от кого
$mail->addAddress('test@ya.ru', 'Вася Петров'); // кому
$mail->Subject = 'Тест';
$mail->msgHTML("<html><body>
<h1>Здравствуйте!</h1>
<p>Это тестовое письмо.</p>
</html></body>");
// Отправляем
if ($mail->send()) {
echo 'Письмо отправлено!';
} else {
echo 'Ошибка: ' . $mail->ErrorInfo;
}
add_action('user_profile_update_errors','check_fields',10,3);
if(!function_exists('check_fields')){
function check_fields($errors,$update,$user){
$users=get_users();
if(count($users)>=3){
$errors->add('max_limit','<strong>ERROR</strong>: '.__('Превышен лимит регистраций','VAB'));
// wp_die("Превышен лимит регистраций");
}return $errors;}}
Обычные thumbnail и тд не пойдут. Так как они просто уменьшают саму картинку,
//получаем в шаблоне:
$attachment_src=wp_get_attachment_image_src(get_post_thumbnail_id(),'thumbnail');
//functions.php
add_filter('wp_handle_upload_prefilter','add_handle_upload');
if(!function_exists('add_handle_upload')){
function add_handle_upload($file){
add_image_size('mysize',600,200,array('center','center'));
return $file;
}}
//получаем в шаблоне:
$attachment_src=wp_get_attachment_image_src(get_post_thumbnail_id(),'mysize');
//functions.php
add_filter('wp_handle_upload_prefilter','add_handle_upload');
if(!function_exists('add_handle_upload')){
function add_handle_upload($file){
$tmp_name=$file['tmp_name'];
$image=new Imagick($tmp_name);
$image->chopImage(0,100,0,0);//отрезаем 100 px сверху
$imageprops=$image->getImageGeometry();//чтобы отрезать снизу надо узнать высоту и отнять 100 px и уже от нее отрезать все то, что ниже
$image->chopImage(0,100,0,$imageprops['height']-100);//отрезаем 100 px снизу
$image->writeImage($tmp_name);//перезаписываем временный файл
return $file;
}}