Плагин Загружает Скрипты и стили на каждую страницу - Даже если они не используются


У меня есть плагин, который использует программирование в стиле класса. Я в полном замешательстве - скрипты загружаются на каждой отдельной странице, даже если плагин не используется на этой странице.

Поскольку плагин должен запускаться только при вызове одного из его коротких кодов, я не понимаю, почему они всегда ставятся в очередь. Код таков:

<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

add_action( 'plugins_loaded', array ( 'Lipstick_Consultation', 'init' ));

if (!class_exists('Lipstick_Consultation')){

//used for the script loader, to load custom jquery at the footer
$plugin_script = "";

class Lipstick_Consultation{

    public static function init() {
        $class = __CLASS__;
        new $class;
    }

    /**
     * @since 1.0
     */
    public function __construct() {

        //get contstants
        $this->setup_constants();

        //get file includes
        $this->includes();

        //register plugin shortcodes
        $this->register_shortcodes();

        //Register Styles
        add_action( 'wp_enqueue_scripts', array( $this, 'register_styles' ) );

        //Register Scripts
        add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );

        $this->page_scripts();

        return $this;
    }

    /**
     * Include our Class files
     *
     * @access private
     * @since 1.0.0
     * @return void
     */
    private function includes() {

        /****SHORTCODES****/
        //[slider_person]
        require_once LC_DIR . 'inc/shortcodes/slider.php';

        //[suggested_colors]
        require_once LC_DIR . 'inc/templates/tmpl-suggestedcolors.php';
    }

    /**
     * Setup plugin constants
     *
     * @access private
     * @since 1.0.0
     * @return void
     */
    private function setup_constants() {

        // Plugin information
        define( 'LC_VERSION',       '1.0.0' ); // Current plugin version
        define( 'LC_URL',           plugin_dir_url( __FILE__ ) );
        define( 'LC_DIR',           plugin_dir_path( __FILE__ ) );

    }

    /**
     * Register Styles
     *
     * @access private
     * @since 1.0.0
     * @return void
     */
    public function register_styles() {

        //main style file
        wp_register_style( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
        wp_enqueue_style( 'consultation_style' );

        //styles for full page plugin
        wp_register_style( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
        wp_enqueue_style( 'lc_full_page_style' );

    }

    /**
     * Register Scripts
     *
     * @access private
     * @since 1.0.0
     * @return void
     */
    public function register_scripts() {
        //Script that makes div have a scrollbar
        wp_register_script( 'lc_slim_scroll', LC_URL . "assets/js/jquery.slimscroll". SUFFIX . ".js", array( 'jquery' ), time() );
        wp_enqueue_script( 'lc_slim_scroll' );


        //Script that makes full width/height/page divs
        wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage". SUFFIX . ".js", array( 'jquery' ), time() );
        wp_enqueue_script( 'lc_full_page' );

    }

    private function register_shortcodes(){
        //slider for "Choose You" Slider
        add_shortcode("lipstick_person", array('Lipstick_Consultation', "shortcode_person_slider"));

        //Template for lipstick color suggestions
        add_shortcode("suggested_colors", array($this, "suggested_colors_template"));
    }

    private function page_scripts(){

        //load fullPage jquery code
        $this->add_full_page_script();

    }

    /*
    *function to echo the script that triggers the plugin
    */
    public function add_script_footer(){
        echo $this->plugin_script;
    } 

    /**********************************************************************/
    /**********************************************************************/
    /*************MAY BE BETTER TO INCLUDE THIS IN ITS OWN FILE************/
    /**********************************************************************/
    /**********************************************************************/

    /*
    * Add script to get the full page effect on all page elements (this is for the page content)
    */
    private function add_full_page_script(){
        ob_start();
    ?>
        <!--jQuery Function to Trigger the plugin for this page-->
        <script type="text/javascript">
        //on document ready
        jQuery(document).ready(function($){
            $('#fullpage').fullpage({
                anchors:['instructions', 'choose-you', 'consultation-suggested-colors', 'all-colors'],
                scrollOverflow: true

                //look into the menu option https://github.com/alvarotrigo/fullPage.js

            });
        });


        </script>

    <?php
        //get jQuery script, set it as global script variable and call the WP callback
        $script = ob_get_contents();
        ob_end_clean();

        //set variable to the script above
        $this->plugin_script = $script;

        //call hook to add script to footer.
        add_action('wp_footer', array($this,'add_script_footer'),20); 

    }
}
}
?>

Если я понимаю, что происходит, на крючке plugins_loaded создается экземпляр плагина. Когда метод построения называется это запросом сценариев. Все это имеет смысл.

При взгляде на другие плагины кажется, что они используют аналогичную структуру, но все же - их файлы сценариев загружаются только тогда, когда их плагин вызывается на этой странице.

Что я делаю не так? Спасибо!

ОБНОВЛЕНИЕ #1

Ребята, я просто не могу понять, как это сделать. Я внес следующие изменения в код:

    public function __construct() {

        //get contstants
        $this->setup_constants();

        //get file includes
        $this->includes();

        //register plugin shortcodes
        $this->register_shortcodes();

        return $this;
    }

    /**
     * Registers the styles and scripts for the shortcodes
     */
    private function register_shortcode_requirements() {

        //Register Styles
        add_action( 'wp_enqueue_scripts', array( $this, 'register_styles' ) );

        //Register Scripts
        add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );

    }

    /**
     * Register Styles
     */
    public function register_styles() {

        //main style file
        wp_register_script( 'consultation_style', LC_URL . "assets/css/style.css", array(), time(), 'all' );
        wp_enqueue_script( 'consultation_style' );

        //styles for full page plugin
        wp_register_script( 'lc_full_page_style', LC_URL . "assets/css/jquery.fullPage.css", array(), time(), 'all' );
        wp_enqueue_script( 'lc_full_page_style' );

    }

    /**
     * Register Scripts
     */
    public function register_scripts() {
        //Script that makes div have a scrollbar
        wp_register_script( 'lc_slim_scroll', LC_URL . "assets/js/jquery.slimscroll". SUFFIX . ".js", array( 'jquery' ), time() );
        wp_enqueue_script( 'lc_slim_scroll' );


        //Script that makes full width/height/page divs
        wp_register_script( 'lc_full_page', LC_URL . "assets/js/jquery.fullPage". SUFFIX . ".js", array( 'jquery' ), time() );
        wp_enqueue_script( 'lc_full_page' );

    }

    private function register_shortcodes(){
        //slider for "Choose You" Slider
        add_shortcode("lipstick_person", array($this,"shortcode_person_slider_caller"));

    }
    /*
    * Calling Function to include scripts and then fire the actual shortcode function contained in separate .php file
     */
    public function shortcode_person_slider_caller($atts, $content){

        //register styles/scripts
        $this->register_shortcode_requirements();

        //run actual function for rendering
        $content = shortcode_person_slider($atts);
        return $content;
    }

Затем в вызывающей функции shortcode_person_slider включена функция в одном из загруженных файлов require_once.

Функция запускается (протестирована с помощью var_dump) в этой функции, и она отображается. Тем не менее, содержимое не отображается на странице (хотя $content содержит всю разметку html).

Кроме того, файлы сценариев/стилей не ставятся в очередь.

При тестировании register_shortcode_requirements() срабатывает, но каждый из крючков wp_enqueue_script не срабатывает.

Есть какие-нибудь советы? Спасибо!

Author: W00tW00t111, 2015-06-12

2 answers

Как уже отмечалось, вы ответили на свой вопрос. Вы говорите программному обеспечению постоянно загружать эти сценарии. Вам нужно контролировать этот процесс. Программное обеспечение - это глупо. Он не может решить, когда подходящее время для загрузки кода. ИТАК...

Поскольку плагин должен запускаться только при вызове одного из его коротких кодов, ...

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

function my_shortcode( $atts, $content = null ) {
    extract(shortcode_atts(array(
            'title'  => '',
           ), $atts));
    static $counter = 0;
    echo $counter++;
    wp_enqueue_script('wp-mediaelement'); 

}
add_shortcode('enq','my_shortcode');

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

Что касается вашей таблицы стилей,

  1. Вы можете загрузить их в нижний колонтитул страницы аналогично сценариям. Это недопустимая разметка, но, как правило, работает.
  2. Вы можете загрузить стили, встроенные в шорткод, что является достойным вариантом, возможно, лучшим.
  3. Вы можете использовать javascript для вставки стилей динамически
  4. Вы можете "предварительно обработать" шорткод, аналогично этому (что является ресурсоемким решением): https://wordpress.stackexchange.com/a/101515/21376
 2
Author: s_ha_dum, 2017-04-13 12:37:38

Вы отвечаете на свой собственный вопрос - скрипты ставятся в очередь, потому что это то, что плагин выполняет каждую загрузку безоговорочно.

Нет никакой логики, которая контролирует, когда это должно произойти или не произойти, это просто происходит всегда.

Если вы внимательно посмотрите на плагин, который делает это более разумно, вы обычно заметите одну из следующих вещей:

  • существует условная проверка методов подключения или самих внутренних методов
  • крючки используемые данные специфичны для определенного контекста
  • очередь вызывается из кода с соответствующей функцией, например, сценарии, необходимые для шорткода, могут быть поставлены в очередь, когда из обработчика шорткода
 0
Author: Rarst, 2015-06-12 15:42:21