Конкретный скрипт Wp Enqueue в wordpress

В поисках плагина я наткнулся на этот веб-сайт.

Я увидел красивую анимацию облаков.

Поэтому я начал поиск в Google, чтобы найти источник кода, и нашел его здесь ... Предварительный просмотр

/JS

<script type="text/javascript" src="js/ThreeWebGL.js"></script>
<script type="text/javascript" src="js/ThreeExtras.js"></script>
<script type="text/javascript" src="js/Detector.js"></script>
<script type="text/javascript" src="js/RequestAnimationFrame.js"></script>

/HTML

<script id="vs" type="x-shader/x-vertex">
    varying vec2 vUv;
    void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
    }
</script>
<script id="fs" type="x-shader/x-fragment">
    uniform sampler2D map;
    uniform vec3 fogColor;
    uniform float fogNear;
    uniform float fogFar;
    varying vec2 vUv;
    void main() {
        float depth = gl_FragCoord.z / gl_FragCoord.w;
        float fogFactor = smoothstep( fogNear, fogFar, depth );
        gl_FragColor = texture2D( map, vUv );
        gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 );
        gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );
    }
</script>
<script type="text/javascript">
    if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
    // Bg gradient
    var canvas = document.createElement( 'canvas' );
    canvas.width = 32;
    canvas.height = window.innerHeight;
    var context = canvas.getContext( '2d' );
    var gradient = context.createLinearGradient( 0, 0, 0, canvas.height );
    gradient.addColorStop(0, "#1e4877");
    gradient.addColorStop(0.5, "#4584b4");
    context.fillStyle = gradient;
    context.fillRect(0, 0, canvas.width, canvas.height);
    document.body.style.background = 'url(' + canvas.toDataURL('image/png') + ')';
    // Clouds
    var container;
    var camera, scene, renderer, sky, mesh, geometry, material,
    i, h, color, colors = [], sprite, size, x, y, z;
    var mouseX = 0, mouseY = 0;
    var start_time = new Date().getTime();
    var windowHalfX = window.innerWidth / 2;
    var windowHalfY = window.innerHeight / 2;
    init();
    animate();
    function init() {
        container = document.createElement( 'div' );
        document.body.appendChild( container );
        camera = new THREE.Camera( 30, window.innerWidth / window.innerHeight, 1, 3000 );
        camera.position.z = 6000;
        scene = new THREE.Scene();
        geometry = new THREE.Geometry();
        var texture = THREE.ImageUtils.loadTexture( 'cloud10.png' );
        texture.magFilter = THREE.LinearMipMapLinearFilter;
        texture.minFilter = THREE.LinearMipMapLinearFilter;
        var fog = new THREE.Fog( 0x4584b4, - 100, 3000 );
        material = new THREE.MeshShaderMaterial( {
            uniforms: {
                "map": { type: "t", value:2, texture: texture },
                "fogColor" : { type: "c", value: fog.color },
                "fogNear" : { type: "f", value: fog.near },
                "fogFar" : { type: "f", value: fog.far },
            },
            vertexShader: document.getElementById( 'vs' ).textContent,
            fragmentShader: document.getElementById( 'fs' ).textContent,
            depthTest: false
        } );
        var plane = new THREE.Mesh( new THREE.Plane( 64, 64 ) );
        for ( i = 0; i < 8000; i++ ) {
            plane.position.x = Math.random() * 1000 - 500;
            plane.position.y = - Math.random() * Math.random() * 200 - 15;
            plane.position.z = i;
            plane.rotation.z = Math.random() * Math.PI;
            plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5;
            GeometryUtils.merge( geometry, plane );
        }
        mesh = new THREE.Mesh( geometry, material );
        scene.addObject( mesh );
        mesh = new THREE.Mesh( geometry, material );
        mesh.position.z = - 8000;
        scene.addObject( mesh );
        renderer = new THREE.WebGLRenderer( { antialias: false } );
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );
        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        window.addEventListener( 'resize', onWindowResize, false );
    }
    function onDocumentMouseMove( event ) {
        mouseX = ( event.clientX - windowHalfX ) * 0.25;
        mouseY = ( event.clientY - windowHalfY ) * 0.15;
    }
    function onWindowResize( event ) {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
    }
    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    function render() {
        position = ( ( new Date().getTime() - start_time ) * 0.03 ) % 8000;
        camera.position.x += ( mouseX - camera.target.position.x ) * 0.01;
        camera.position.y += ( - mouseY - camera.target.position.y ) * 0.01;
        camera.position.z = - position + 8000;
        camera.target.position.x = camera.position.x;
        camera.target.position.y = camera.position.y;
        camera.target.position.z = camera.position.z - 1000;
        renderer.render( scene, camera );
    }
</script>

Мой вопрос сейчас:

Я хотел бы настроить его на своем локальном сайте, чтобы протестировать его на elementor.

Я буду вызывать скрипт с html-виджетом.

Проблема, которую я знаю, есть опция wp_enqueue_script в functions.php, и скрипт идет туда.

но я не могу понять точную процедуру. Я не мог часами настраивать сценарии...

Можете ли вы показать мне, как его интегрировать? Мне нужен хороший пример использования этих скриптов. раз и навсегда понять, как интегрировать скрипты в дочерние темы WordPress.

Мои настройки: чистая установка wordpress с пустой темой hello и это установлен дочерний элемент.

Обновить

давайте немного разовьем тему Я проделал эти манипуляции в functions.php

function my_scripts_method() {
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/ThreeWebGL.js',array( 'jquery' ));
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/ThreeExtras.js',array( 'jquery' ));
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/Detector.js',array( 'jquery' ));
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/RequestAnimationFrame.js',array( 'jquery' ));

}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

Вроде работает.. надеюсь скрипты загрузились.

У меня просто есть сообщение в консоли Chrome:

Uncaught ReferenceError: Детектор не определен по адресу (индекс): 117

Я думаю, потому что я еще не поставил html?

что вы думаете о сниппете?

Я использую его для создания и добавления_шорткода

что-то в этом роде... как вы думаете, это безопасно?

    add_shortcode( 'amazing clouds', function () {

<script id="vs" type="x-shader/x-vertex">
    varying vec2 vUv;
    void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
    }
</script>
<script id="fs" type="x-shader/x-fragment">
    uniform sampler2D map;
    uniform vec3 fogColor;
    uniform float fogNear;
    uniform float fogFar;
    varying vec2 vUv;
    void main() {
        float depth = gl_FragCoord.z / gl_FragCoord.w;
        float fogFactor = smoothstep( fogNear, fogFar, depth );
        gl_FragColor = texture2D( map, vUv );
        gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 );
        gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );
    }
</script>
<script type="text/javascript">
    if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
    // Bg gradient
    var canvas = document.createElement( 'canvas' );
    canvas.width = 32;
    canvas.height = window.innerHeight;
    var context = canvas.getContext( '2d' );
    var gradient = context.createLinearGradient( 0, 0, 0, canvas.height );
    gradient.addColorStop(0, "#1e4877");
    gradient.addColorStop(0.5, "#4584b4");
    context.fillStyle = gradient;
    context.fillRect(0, 0, canvas.width, canvas.height);
    document.body.style.background = 'url(' + canvas.toDataURL('image/png') + ')';
    // Clouds
    var container;
    var camera, scene, renderer, sky, mesh, geometry, material,
    i, h, color, colors = [], sprite, size, x, y, z;
    var mouseX = 0, mouseY = 0;
    var start_time = new Date().getTime();
    var windowHalfX = window.innerWidth / 2;
    var windowHalfY = window.innerHeight / 2;
    init();
    animate();
    function init() {
        container = document.createElement( 'div' );
        document.body.appendChild( container );
        camera = new THREE.Camera( 30, window.innerWidth / window.innerHeight, 1, 3000 );
        camera.position.z = 6000;
        scene = new THREE.Scene();
        geometry = new THREE.Geometry();
        var texture = THREE.ImageUtils.loadTexture( 'cloud10.png' );
        texture.magFilter = THREE.LinearMipMapLinearFilter;
        texture.minFilter = THREE.LinearMipMapLinearFilter;
        var fog = new THREE.Fog( 0x4584b4, - 100, 3000 );
        material = new THREE.MeshShaderMaterial( {
            uniforms: {
                "map": { type: "t", value:2, texture: texture },
                "fogColor" : { type: "c", value: fog.color },
                "fogNear" : { type: "f", value: fog.near },
                "fogFar" : { type: "f", value: fog.far },
            },
            vertexShader: document.getElementById( 'vs' ).textContent,
            fragmentShader: document.getElementById( 'fs' ).textContent,
            depthTest: false
        } );
        var plane = new THREE.Mesh( new THREE.Plane( 64, 64 ) );
        for ( i = 0; i < 8000; i++ ) {
            plane.position.x = Math.random() * 1000 - 500;
            plane.position.y = - Math.random() * Math.random() * 200 - 15;
            plane.position.z = i;
            plane.rotation.z = Math.random() * Math.PI;
            plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5;
            GeometryUtils.merge( geometry, plane );
        }
        mesh = new THREE.Mesh( geometry, material );
        scene.addObject( mesh );
        mesh = new THREE.Mesh( geometry, material );
        mesh.position.z = - 8000;
        scene.addObject( mesh );
        renderer = new THREE.WebGLRenderer( { antialias: false } );
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );
        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        window.addEventListener( 'resize', onWindowResize, false );
    }
    function onDocumentMouseMove( event ) {
        mouseX = ( event.clientX - windowHalfX ) * 0.25;
        mouseY = ( event.clientY - windowHalfY ) * 0.15;
    }
    function onWindowResize( event ) {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
    }
    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    function render() {
        position = ( ( new Date().getTime() - start_time ) * 0.03 ) % 8000;
        camera.position.x += ( mouseX - camera.target.position.x ) * 0.01;
        camera.position.y += ( - mouseY - camera.target.position.y ) * 0.01;
        camera.position.z = - position + 8000;
        camera.target.position.x = camera.position.x;
        camera.target.position.y = camera.position.y;
        camera.target.position.z = camera.position.z - 1000;
        renderer.render( scene, camera );
    }
</script>
} );

Все стало очень сложно очень быстро.

Я надеюсь, что кто-нибудь придет и покажет нам, как интегрировать его в страницу WordPress.

(с elementor бонус)


person neosan    schedule 26.12.2019    source источник


Ответы (1)


Виджет HTML удалит теги php по соображениям безопасности. Но у вас есть несколько вариантов, которые позволят вам достичь своей цели. Вот три:

  1. Редактируйте функции вашей дочерней темы .php файл, чтобы разрешить использование php в виджете. (Плохая идея)

  2. Напишите свой собственный виджет, который ставит в очередь нужный вам скрипт. (лучше идея)

  3. Не используйте виджет вообще. Просто добавьте скрипт на нужные страницы с помощью плагина Advanced Custom Fields. (ИМХО лучшая идея)

И поскольку вы спрашивали о загрузке JS, вот вам хороший ресурс.
И вот еще на тему wp_enqueue_scripts() .


Редактировать: пошаговые инструкции для плагина ACF:

  1. Установите плагин Advanced Custom Fields
  2. Перейдите в настройки пользовательских полей и нажмите «Добавить новое».
  3. Назовите группу полей, например, «Настройки JavaScript».
  4. Создайте правила, чтобы ограничить, где будут отображаться поля и кто их увидит.
  5. Рядом со стилем выберите «Стандартный» (метабокс WP).
  6. Нажмите + Добавить поле
  7. Назовите его «Скрипт заголовка».
  8. Измените тип поля на «Текстовая область».
  9. Измените форматирование на «Преобразовать HTML в теги».
  10. Повторите с шага 6, но на этот раз назовите его «Сценарий нижнего колонтитула».
  11. Опубликовать группу полей
  12. В header.php прямо перед закрывающим тегом </head> добавьте: <?php the_field('header_script'); ?>
  13. В файле footer.php прямо перед закрывающим тегом </body> добавьте: <?php the_field(‘footer_script'); ?>
  14. Поместите файлы javascript в папку на вашем сервере (желательно в дочерней теме).
  15. Свяжите свой javascript в новых полях на своей странице, используя обычные теги html <script>

Примечание: скопируйте файлы header.php и footer.php в дочернюю тему и внесите там изменения (шаги 12 и 13), чтобы не потерять эти изменения при обновлении темы.

person thingEvery    schedule 26.12.2019
comment
спасибо за ваш ответ, я сделал обновление. У меня тоже есть acf pro, и я использую его каждый день. можешь объяснить метод? Я никогда не думал, что это возможно с acf. - person neosan; 26.12.2019
comment
@newneo Я отредактировал свой ответ, включив в него пошаговые инструкции. - person thingEvery; 26.12.2019