Skip to content

Instantly share code, notes, and snippets.

@eto4detak
Last active May 26, 2019 21:18
Show Gist options
  • Save eto4detak/aaf8041fc2e075a595bc671f17b280aa to your computer and use it in GitHub Desktop.
Save eto4detak/aaf8041fc2e075a595bc671f17b280aa to your computer and use it in GitHub Desktop.
ajax newwp
<?php
///////////////////////////////////////////////////////////////////////////////////////////
/////// ADMIN PAGE SETTINGS
///////////////////////////////////////////////////////////////////////////////////////////
add_action('admin_menu', 'access_register_wc_submenu_page');
function access_register_wc_submenu_page() {
add_submenu_page( 'edit.php?post_type=product', 'Страна для подкатегории', 'Страна для подкатегории', 'manage_options', 'access-product-attribute-state', 'access_my_wc_submenu_page_callback' );
}
function access_my_wc_submenu_page_callback() {
// контент страницы
$args = array(
'taxonomy' => 'product_cat',
);
$terms = get_terms( $args );
echo '<div class="wrap"><h3 class="edit-attributes__description">Изменить страну производителя для подкатегории</h3>';
if( $terms && ! is_wp_error($terms) ){
echo "<div class='edit-attributes__main'>";
foreach( $terms as $term ){
if($term->parent === 0){
echo "<div class='taxonomy-name'><span data-slug='{$term->slug}' class='edit-attributes__header'>Категория: ". $term->name ."</span>";
foreach ($terms as $t_ch) {
if($term->term_id === $t_ch->parent ){
echo "<div class='term-name'><div style='width:200px;display:inline-block'>-{$t_ch->name}</div><input class='input' value='" . get_term_meta( $t_ch->term_id, 'strana-proiz', true ) . "' data-id='{$t_ch->term_id}' data-term='{$t_ch->slug}' type='text' data-cat='{$term->slug}'><button class='term-update'>Обновить</button></div>";
}
}
echo "</div>";//term-name taxonomy-name
}
}
echo "</div>";//edit-attributes__main
}
// vardump($terms);
echo '</div>';
?>
<script type='text/javascript'>
(function($) {
jQuery('.term-update').on("click", function(e) {
var $input = jQuery(this).siblings('input');
var cat = $input.data('cat');
var term = $input.data('term');
var id = $input.data('id');
var value = $input.val();
console.log(cat);
console.log(term);
console.log(id);
console.log(value);
var dataTerm = {};
dataTerm.cat = cat;
dataTerm.term = term;
dataTerm.vid = id;
dataTerm.val = value;
var str = JSON.stringify(dataTerm);
console.log(str);
// JSON.parse(data);
var data = {
action: 'c_add_product',
dataType: 'json',
consData: str,
nonce_code : myajax.nonce
};
jQuery.post( myajax.url, data, function(response) {
console.log('Добален ' + response);
});
});
})(jQuery);
</script>
<?php
}
if( wp_doing_ajax() ){
add_action('wp_ajax_c_add_product', 'construct_add_product');
add_action('wp_ajax_nopriv_c_add_product', 'construct_add_product');
}
function construct_add_product() {
global $post;
if( ! wp_verify_nonce( $_POST['nonce_code'], 'booking-nonce' ) ) die( 'Stop!');
$json = wp_unslash( $_POST['bookingData']);
$obj = json_decode($json);
echo json_encode( $obj);
access_find_cat_attribute_woocommerce($obj);
wp_die();
}
// найти атрибуты подкатегорий(1го уровня) woocommerce
function access_find_cat_attribute_woocommerce($obj='')
{
$args = array(
'taxonomy' => 'product_cat',
);
$terms = get_terms( $args );
if( $terms && ! is_wp_error($terms) ){
foreach( $terms as $term ){
if($term->parent === 0 && $term->slug === $obj->cat){
foreach ($terms as $t_ch) {
if($term->term_id === $t_ch->parent && $t_ch->slug === $obj->term ){
access_set_attribute_woocommerce($t_ch,$obj->val);
}
}
}
}
}
}
//обновить атрибут продукта woocommerce
function access_set_attribute_woocommerce($cat='', $value = ''){
global $post;
// $custom_attribute = 'pa_strana-proizvodstva';
$custom_attribute = htmlspecialchars(stripslashes('pa_strana-proizvodstva'));
$value_attr = htmlspecialchars(stripslashes($value));
//vardump($cat->name);
$args = array(
'post_type' => 'product',
'product_cat' => $cat->slug,
'posts_per_page'=>-1
);
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
// vardump('+1' . $post->post_title);
wp_delete_object_term_relationships( get_the_ID(), $custom_attribute );
$term_taxonomy_ids = wp_set_object_terms( get_the_ID(), $value_attr, $custom_attribute, true );
$attributes = get_post_meta( $post->ID, '_product_attributes' );
// vardump($attributes);
// vardump('-------');
// vardump($attributes[0][ $custom_attribute ]);
$attributes[0][ sanitize_title( $custom_attribute ) ] = array(
'name' => wc_clean( $custom_attribute ),
'value'=>'',
'is_visible' => '1',
'is_variation' => '0',
'is_taxonomy' => '1'
);
update_post_meta(get_the_ID(), '_product_attributes', $attributes[0] );
endwhile;
}
//vardump('==========================');
wp_reset_query();
}
/*========================================================
* Ajax
========================================================*/
//wp_enqueue_scripts
add_action( 'admin_enqueue_scripts', 'construct_myajax_data');
function construct_myajax_data(){
wp_localize_script( 'jquery', 'myajax',
array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('myajax-nonce')
)
);
}
//print_footer_scripts
add_action('admin_print_footer_scripts', 'construct_action_javascript', 99);
function construct_action_javascript() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: 1234
};
// с версии 2.8 'ajaxurl' всегда определен в админке
jQuery.post( ajaxurl, data, function(response) {
alert('Получено с сервера: ' + response);
});
});
</script>
<?php
}
// file
// ajax file img
$('.load-btn').on('click', '', function(event) {
event.preventDefault();
$(this).parent().find('input[type=file].download').click();
});
var files; // переменная. будет содержать данные файлов
// // заполняем переменную данными, при изменении значения поля file
$('input[type=file].download').on('change', function(){
files = this.files;
event.stopPropagation(); // остановка всех текущих JS событий
event.preventDefault(); // остановка дефолтного события для текущего элемента - клик для <a> тега
// ничего не делаем если files пустой
if( typeof files == 'undefined' ) return;
// создадим данные файлов в подходящем для отправки формате
var data = new FormData();
$.each( files, function( key, value ){
data.append( key, value );
});
// добавим переменную идентификатор запроса
data.append( 'action', 'ajax_upload_files' );
data.append( 'nonce', formPsych.nonce );
// data.append( 'post_id', $('body').attr('class').match(/postid-([0-9]+)/)[1] );
var $reply = $('.ajax-reply');
// AJAX запрос
// $reply.text( 'Загружаю...' );
console.log('test');
console.log(data);
$.ajax({
url : formPsych.url,
type : 'POST',
data : data,
cache : false,
dataType : 'json',
// отключаем обработку передаваемых данных, пусть передаются как есть
processData : false,
// отключаем установку заголовка типа запроса. Так jQuery скажет серверу что это строковой запрос
contentType : false,
// функция успешного ответа сервера
success : function( respond, status, jqXHR ){
console.log('succ');
// ОК
if( respond.success ){
$.each( respond.data, function( key, val ){
console.log(key );
console.log(val );
$('.for-photo img').attr( "src", val );
// $reply.append( '<p>'+ val +'</p>' );
} );
}
// error
else {
$reply.text( 'ОШИБКА: ' + respond.error );
}
},
// функция ошибки ответа сервера
error: function( jqXHR, status, errorThrown ){
console.log('status' );
console.log(jqXHR );
console.log(status );
console.log(errorThrown );
}
});
});
// php
function ajax_upload_files()
{
check_ajax_referer( 'form-psych-nonce', 'nonce' ); // защита
// if( empty($_FILES) )
// wp_send_json_error( 'Файлов нет...' );
// $post_id = (int) $_POST['post_id'];
// ограничим размер загружаемой картинки
$sizedata = getimagesize( $_FILES['upfile']['tmp_name'] );
$max_size = 2000;
if( $sizedata[0]/*width*/ > $max_size || $sizedata[1]/*height*/ > $max_size )
wp_send_json_error( __('Картинка не может быть больше чем '. $max_size .'px в ширину или высоту...','km') );
// обрабатываем загрузку файла
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
// фильтр допустимых типов файлов - разрешим только картинки
add_filter( 'upload_mimes', function( $mimes ){
return [
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
];
} );
$uploaded_imgs = array();
foreach( $_FILES as $file_id => $data ){
$attach_id = media_handle_upload( $file_id, $post_id );
// ошибка
if( is_wp_error( $attach_id ) )
$uploaded_imgs[] = 'Ошибка загрузки файла `'. $data['name'] .'`: '. $attach_id->get_error_message();
else
$uploaded_imgs[] = wp_get_attachment_url( $attach_id );
}
wp_send_json_success( $uploaded_imgs );
}
// /////////////////////// ajax data
ajaxurl = ajaxcalls_vars.admin_url + 'admin-ajax.php';
jQuery('#listing_ajax_container').empty();
jQuery('#listing_loader').show();
var nonce = jQuery('#wprentals_ajax_filtering').val();
jQuery.ajax({
type: 'POST',
url: ajaxurl,
dataType: 'json',
data: {
'action' : 'wpestate_custom_ondemand_pin_load_new',
'search_location' : search_location_filter_autointernal,
'all_fields' : all_fields,
'apartment_number' : apartment_number,
'stype' : stype,
'advanced_city' : city,
'advanced_area' : area,
'advanced_country' : country,
'property_admin_area' : property_admin_area,
'all_checkers' : all_checkers,
'newpage' : newpage,
'postid' : postid,
'keyword_search' : keyword_search,
'geo_lat' : geo_lat,
'geo_long' : geo_long,
'geo_rad' : geo_rad,
'pan_ne_lat' : pan_ne_lat,
'pan_ne_long' : pan_ne_long,
'pan_sw_lat' : pan_sw_lat,
'pan_sv_long' : pan_sv_long,
'move_map' : move_map,
'security' : nonce,
},
success: function (data) {
jQuery('#advanced_search_map_list').removeClass('movetofixed');
jQuery('#listing_loader').hide();
jQuery('.listing_loader_title').show();
jQuery('#listing_ajax_container').empty().append(data.response);
jQuery('.pagination_nojax').remove();
wpestate_restart_js_after_ajax();
wpestate_lazy_load_carousel_property_unit();
var new_markers = jQuery.parseJSON(data.markers);
if (infoBox !== null) {
infoBox.close();
}
if(typeof(move_map)!=='undefined'){
wpestate_set_filter_pins_ondemand(map, new_markers);
}else{
wpestate_set_filter_pins(map, new_markers);
}
is_fit_bounds_zoom=0;
if( jQuery("#geolocation_search").length > 0 && initial_geolocation_circle_flag === 0){
var place_lat = jQuery('#geolocation_lat').val();
var place_lng = jQuery('#geolocation_long').val();
if(place_lat!=='' && place_lng!=''){
initial_geolocation_circle_flag=1;
wpestate_geolocation_marker(place_lat,place_lng);
}
}
},
error: function (errorThrown) {}
});//end ajax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment