Неправильно работают скрипты при подключении
я впервые столкнулся с WP, так что прошу помощи. Есть js файлы, где главный - site.js
import {Subscription} from "./subscription/subscription.js";
import {Annual} from "./subscription/annual.js";
import {Validation} from "./validation/validation.js";
import {Account} from "./account/account.js";
jQuery(function() {
let subscription = new Subscription();
subscription.executeAddons();
subscription.showAddons();
subscription.checkChangeSelectedAddons();
subscription.checkChangeSelectedSubAddons();
let v = new Validation();
v.execute();
let annual = new Annual();
annual.setAnnual(subscription);
subscription.checkChangeSlider(subscription);
subscription.checkChangeStaffValue(subscription);
let account = new Account();
account.checkChange();
v.submitForm(subscription, account);
});
Так же есть модули, которые вставляются в site.js. Пример модуля:
import { Monthly } from "../subscription/monthly.js";
import { Annual } from "../subscription/annual.js";
export class Slider {
isChecked = true;
annual = new Annual();
monthly = new Monthly();
checkChange(subscription) {
$('#s_toggle').on('change', () => {
this.isChecked = !this.isChecked;
if (!this.isChecked) {
$('.toggle-slider').css('background-color', 'white');
$('.toggle-slider:before').css('transform', 'translateX(30px)');
$('.toggle-label-left').css('color', 'black');
$('.toggle-label-right').css('color', '#81d504');
this.monthly.setMonthly(subscription);
subscription.calculateAddons();
} else {
$('.toggle-slider').css('background-color', 'white');
$('.toggle-slider:before').css('transform', 'translateX(0)');
$('.toggle-label-left').css('color', '#81d504');
$('.toggle-label-right').css('color', 'black');
this.annual.setAnnual(subscription);
subscription.calculateAddons();
}
});
}
}
Простой html, css, js не на WP, то он работает хорошо, а вот на WP все будто ломается. css стили не все правильно становятся, js - не работает слайдер и т.д. Возможно, что я неправильно подключил это все. function.php:
<?php
/**
* Functions and definitions.
*
* @link https://livecomposerplugin.com/themes/
*
* @package LC Blank
*/
// Delcare Header/Footer compatibility.
define( 'DS_LIVE_COMPOSER_HF', true );
define( 'DS_LIVE_COMPOSER_HF_AUTO', false );
// Content Width ( WP requires it and LC uses is to figure out the wrapper width ).
if ( ! isset( $content_width ) ) {
$content_width = 1180;
}
if ( ! function_exists( 'lct_theme_setup' ) ) {
/**
* Basic theme setup.
*/
function lct_theme_setup() {
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
// Enable Post Thumbnails ( Featured Image ).
add_theme_support( 'post-thumbnails' );
// Enable support for HTML5 markup.
add_theme_support( 'html5', array( 'comment-list', 'search-form', 'comment-form' ) );
}
}
add_action( 'after_setup_theme', 'lct_theme_setup' );
/**
* Load JS and CSS files.
*/
function lct_load_scripts() {
wp_enqueue_style( 'lct-base-style', get_stylesheet_uri(), array(), '1.0' );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'site', get_template_directory_uri() . '/js/site.js', array( 'jquery' ), false, false );
wp_enqueue_script( 'slider', get_template_directory_uri() . '/js/slider/slider.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'annual', get_template_directory_uri() . '/js/subscription/annual.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'monthly', get_template_directory_uri() . '/js/subscription/monthly.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'subscription', get_template_directory_uri() . '/js/subscription/subscription.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'account', get_template_directory_uri() . '/js/account/account.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'validation', get_template_directory_uri() . '/js/validation/validation.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'addon', get_template_directory_uri() . '/js/subscription/addon.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'subAddon', get_template_directory_uri() . '/js/subscription/subAddon.js', array( 'jquery' ), false, true );
}
add_action( 'wp_enqueue_scripts', 'lct_load_scripts' );
add_filter( 'script_loader_tag', 'add_type_attribute', 10, 3 );
function add_type_attribute( $tag, $handle, $src ) {
// Если это не ваш скрипт, возвращаем исходный тег
if ( ! in_array( $handle, array( 'site', 'slider', 'annual', 'monthly', 'subscription', 'account', 'validation', 'addon', 'subAddon' ), true ) ) {
return $tag;
}
// Добавляем атрибут type="module" к вашим скриптам
$tag = str_replace( '<script', '<script type="module"', $tag );
return $tag;
}
function my_enqueue_scripts() {
wp_localize_script( 'site', 'my_ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
if ( ! defined( 'DS_LIVE_COMPOSER_VER' ) ) {
/**
* Admin Notice
*/
function lct_notification() {
?>
<div class="error">
<p><?php printf( __( '%sLive Composer%s plugin is %srequired%s and has to be active for this theme to function.', 'lc-blank' ), '<a target="_blank" href="https://wordpress.org/plugins/live-composer-page-builder/">', '</a>', '<strong>', '</strong>' ); ?></p>
</div>
<?php }
add_action( 'admin_notices', 'lct_notification' );
}
/**
* Proper <title> for header.php - Pass your seperator in header.php. Default: '|'
*/
function lct_title( $sep ) {
the_title();
echo ' ' . $sep . ' ';
bloginfo( 'name ' );
}
function get_access_token(){
// Параметры запроса
$url = 'adsas';
$method = 'POST';
$data = array(
);
// Выполнение запроса
$response = wp_remote_post( $url, array(
'method' => $method,
'body' => $data
) );
if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
$body = wp_remote_retrieve_body( $response );
$json = json_decode( $body );
$access_token = $json->access_token;
return $access_token;
// Обработка успешного ответа
// Действия, которые нужно выполнить с полученным $access_token
// ...
// Возвращаем ответ в формате JSON
wp_send_json( array( 'access_token' => $access_token ) );
} else {
// Обработка ошибок
$error_message = is_wp_error( $response ) ? $response->get_error_message() : 'Unknown error';
wp_send_json_error( $error_message );
}
}
function request1($url) {
$access_token = get_access_token();
// $headers = array(
//
// 'X-com-subscriptions-organizationid' => '00000'
// );
// Параметры запроса
// $args = array(
// 'headers' => $headers
// );
// Выполнение запроса
$response = wp_remote_get($url);
// Проверка наличия ошибок
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
wp_send_json_error($error_message);
}
// Обработка ответа
$html = wp_remote_retrieve_body($response);
$startString = 'https://fasfsa.com/subscribe/';
$endString = '<';
$posStart = strpos($html, $startString);
if ($posStart !== false) {
$posEnd = strpos($html, $endString, $posStart);
if ($posEnd !== false) {
$substring = substr($html, $posStart, $posEnd - $posStart);
return $substring;
}
}
return $html;
}
function request2() {
$access_token = get_access_token();
// Отправка запроса 2 с использованием access token
// ...
// Обработка ответа запроса 2
}
function request3() {
$access_token = get_access_token();
// Отправка запроса 3 с использованием access token
// ...
// Обработка ответа запроса 3
}
function my_custom_action_callback() {
$request_type = isset($_GET['request_type']) ? $_GET['request_type'] : '';
$url = isset($_GET['url']) ? $_GET['url'] : '';
$response = '';
// Выполнение различных запросов в зависимости от типа запроса
if ($request_type === 'request1') {
$response = request1($url);
} elseif ($request_type === 'request2') {
// Обработка запроса 2
} elseif ($request_type === 'request3') {
// Обработка запроса 3
} else {
// Обработка некорректного типа запроса
}
// Отправка ответа
wp_send_json($response);
}
add_action('wp_ajax_my_custom_action', 'my_custom_action_callback');
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_action_callback');
Что не так с подключением?
Источник: Stack Overflow на русском