Support » Developing with WordPress » Fix “wp_register_script was called incorrectly” issue

  • Resolved chantaspell

    (@chantaspell)


    From an online tutorial I have made a plugin that puts a read me later button at the end of each post which saves the post ID to the userMeta table. It works, but throws an error:

    wp_register_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks

    I have isolated my new plugin as the cause of this problem and tried with different themes. I have searched on this and found that the usual solution is to wrap all scripts and styles in a function and hook that function to the target enqueue action. But that’s what this code does (isn’t it?) and the error is persisting.

    Here’s the code:

    define( 'RML_DIR', plugin_dir_path( __FILE__ ) );
    require( RML_DIR.'widget.php' );
    
    class ReadMeLater {
        /**
         * Action hooks
         */
        public function rml_run() {
    
            // Enqueue plugin styles and scripts
            add_action( 'plugins_loaded', array( $this, 'rml_scripts' ) );
            add_action( 'plugins_loaded', array( $this, 'rml_styles' ) );
    
            // Setup filter hook to show Read Me Later link
            add_filter( 'the_excerpt', array( $this, 'rml_button' ) );
            add_filter( 'the_content', array( $this, 'rml_button' ) );
    
            // Setup Ajax action hook
            add_action( 'wp_ajax_read_me_later', array( $this, 'read_me_later' ) );
    
        } 
    
        /**
         * Register plugin styles and scripts
         */
        public function register_rml_scripts() {
            wp_register_script( 'rml-script', plugins_url( 'js/read-me-later.js', __FILE__ ), array('jquery'), null, true );
            wp_register_style( 'rml-style', plugin_dir_url( __FILE__ ) .'css/read-me-later.css' );
        }
    
        /**
         * Enqueues plugin-specific scripts.
         */
        public function rml_scripts() {        
            wp_enqueue_script( 'rml-script' );
            wp_localize_script( 'rml-script', 'rml_obj', array( 
                'ajax_url' => admin_url('admin-ajax.php'),
                'check_nonce' => wp_create_nonce('rml-nonce')
            ) );
        }
    
        /**
         * Enqueues plugin-specific styles.
         */
        public function rml_styles() {         
            wp_enqueue_style( 'rml-style' ); 
        } 
    
        /**
         * Adds a read me later button at the bottom of each post excerpt that allows logged in users
         * to save those posts in their read me later list.
         *
         * @param string $content
         * @return string
         */
        public function rml_button( $content ) {
    
            // Show read me later link only when user is logged in
            if ( is_user_logged_in() && get_post_type() == post ) {
                $html .= '<a href="#" class="rml_bttn" data-id="' . get_the_id() . '">Read Me Later</a>';
                $content .= $html;
            }
            return $content;
    
        } 
    
        /**
         * Hook into wp_ajax_ to save post ids, then display those posts using get_posts() function
         *
         * @access public
         * @return mixed
         */
        public function read_me_later() {
    
            check_ajax_referer( 'rml-nonce', 'security' );
            $rml_post_id = $_POST['post_id']; 
            $echo = array();
            $new_word =$_POST['new_word'];
    
            global $wpdb;
            global $tefl_db_version;
    
            $table_name = $wpdb->prefix . 'userWordsNew';
    
            $charset_collate = $wpdb->get_charset_collate();
    
            $sql = "CREATE TABLE $table_name (
                id mediumint(9) NOT NULL AUTO_INCREMENT,
                time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
                name tinytext NOT NULL,
                text text NOT NULL,
                url varchar(55) DEFAULT '' NOT NULL,
                PRIMARY KEY  (id)
            ) $charset_collate;";
                require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
            dbDelta( $sql );
    
            add_option( 'tefl_db_version', $tefl_db_version );
    
            /* add data */
            global $wpdb;
            global $current_user;
            wp_get_current_user();
    
            if ( is_user_logged_in() ) { 
                $thisUser = $current_user->user_login;
            }
            else {
                wp_loginout();
            }
    
            $student_name = $thisUser;
            $myWord_text = $new_word;
    
            $table_name = $wpdb->prefix . 'userWordsNew';
    
            $wpdb->insert( 
                $table_name, 
                array( 
                    'time' => current_time( 'mysql' ), 
                    'name' => $student_name, 
                    'text' => $myWord_text, 
                ) 
            );
    
            if ( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
                $value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
            }
    
            if ( $value ) {
                $echo = $value;
                array_push( $echo, $rml_post_id );
            }
            else {
                $echo = array( $rml_post_id );
            }
    
            update_user_meta( wp_get_current_user()->ID, 'rml_post_ids', $echo );
            $ids = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
    
            function limit_words($string, $word_limit) {
                $words = explode(' ', $string);
                return implode(' ', array_slice($words, 0, $word_limit));
            }
    
            // Query read me later posts
            $args = array( 
                'post_type' => 'post',
                'orderby' => 'DESC', 
                'posts_per_page' => -1, 
                'numberposts' => -1,
                'post__in' => $ids
            );
    
            $rmlposts = get_posts( $args );
            if ( $ids ) :
                global $post;
                foreach ( $rmlposts as $post ) :
                    setup_postdata( $post );
                    $img = wp_get_attachment_image_src( get_post_thumbnail_id() );
                    ?>
                    <div class="rml_posts">                 
                        <div class="rml_post_content">
                            <h5><a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?></a></h5>
                            <p><?php echo limit_words(get_the_excerpt(), '20'); ?></p>
                        </div>
                        <img src="<?php echo $img[0]; ?>" alt="<?php echo get_the_title(); ?>" class="rml_img">                 
                    </div>
                <?php 
                endforeach; 
                wp_reset_postdata();
            endif;
    
            // Always die in functions echoing Ajax content
            die();
    
        }
    }
    $rml = new ReadMeLater();
    $rml->register_rml_scripts();
    $rml->rml_run();

    Many thanks for any suggestions on how I can clear this error!

Viewing 6 replies - 1 through 6 (of 6 total)
  • strub

    (@strub)

    You should really know what are you doing and not copy/pasting code.

    This code has many security issues and errors.
    I would recommend learning the basics first before writing plugins.

    But do not take WP for learning PHP as reference.

    Pixelbart

    (@pixelbart)

    Use

    add_action( 'wp_enqueue_scripts', array( $this, 'rml_scripts' ) ); and
    add_action( 'wp_enqueue_scripts', array( $this, 'rml_styles' ) );

    insteed of

    add_action( 'plugins_loaded', array( $this, 'rml_scripts' ) ); and
    add_action( 'plugins_loaded', array( $this, 'rml_styles' ) );

    inside your constructor or rml_run method.

    Ref: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts

    • This reply was modified 1 year ago by Pixelbart.
    chantaspell

    (@chantaspell)

    Thanks @pixelbart!
    That takes away some of the errors, but it still gives the same message for this function:

    public function register_rml_scripts() {
            wp_register_script( 'rml-script', plugins_url( 'js/read-me-later.js', __FILE__ ), array('jquery'), null, true );
            wp_register_style( 'rml-style', plugin_dir_url( __FILE__ ) .'css/read-me-later.css' );
        }

    I’ve read the wp_register_script doc linked to from the link you gave me, but all seems to be fine (i tried changing the $in_footer param to false ).

    Any ideas?

    Pixelbart

    (@pixelbart)

    @chantaspell sorry i forgot this method. Add this:

    add_action('wp_enqueue_scripts', array( $this, 'register_rml_scripts' ) );

    inside

    public function rml_run() { // after this

    • This reply was modified 12 months ago by Pixelbart.
    • This reply was modified 12 months ago by Pixelbart.
    chantaspell

    (@chantaspell)

    Ah thank you! That’s perfect, and I learned something too. Despite what the previous poster said, I think getting stuck in and having a go is a good way to learn. Many thanks for your time.

    Pixelbart

    (@pixelbart)

    Great to hear! Have fun with WordPress! 🙂

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Fix “wp_register_script was called incorrectly” issue’ is closed to new replies.