Is there any alternative way to enqueue scripts in wordpress? - php

After solving all problems I am stuck at a very simple problem in WordPress. That is enqueueing an stylesheet and js script. I am desperately looking for a solution. I don't know why this is not working. I think I am following the rules in codex but it's not loading anyways. Even I open the page source code to find those files but didn't find.
File name and locations are below:
popup_plugin
|---- assets\
|---css\
|--- styles.css
And js structure is same as above
Now here is the code i am trying.I am using singleton pattern to instantiate class.
add_action( 'plugins_loaded', array(SMARTPOPUP::getInstance(), 'init') );
class SMARTPOPUP
{
private static $instance = null;
public function init(){
add_action('wp_enqueue_scripts', array($this, 'frontEndAssets'));
}
public function frontEndAssets(){
wp_enqueue_style(
'wpsgdprcss',
plugin_dir_url( __FILE__ ) . 'assets/css/styles.css',
array()
);
wp_enqueue_script(
'wpsgdprjs',
plugin_dir_url( __FILE__ ) . 'assets/js/scripts.js',
array(),
false
);
$localizedata = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'noncesecure' => wp_create_nonce(WP_SMART_GDPR_SLUG),
);
wp_localize_script( 'wpsgdprjs', 'wpsgdprdata', $localizedata );
}
public static function getInstance(){
if(!isset(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}

try below code
add_action( 'plugins_loaded', array(SMARTPOPUP::getInstance(), 'init') );
class SMARTPOPUP
{
private static $instance = null;
public function init(){
add_action('wp_enqueue_scripts', array($this, 'frontEndAssets'));
}
public function frontEndAssets(){
wp_enqueue_style( 'wpsgdprcss');
wp_register_script('wpsgdprcss',plugin_dir_url( __FILE__ ) . 'assets/css/styles.css',array() );
wp_register_script( 'wpsgdprjs',plugin_dir_url( __FILE__ ) . 'assets/js/scripts.js',array(),false );
wp_enqueue_script( 'wpsgdprjs');
$localizedata = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'noncesecure' => wp_create_nonce(WP_SMART_GDPR_SLUG),
);
wp_localize_script( 'wpsgdprjs', 'wpsgdprdata', $localizedata );
}
public static function getInstance(){
if(!isset(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}

function custom_plugin_enqueue() {
wp_enqueue_style( 'wpsgdprcss', plugin_dir_url( __FILE__ ) . 'assets/css/styles.css' );
wp_enqueue_script( 'wpsgdprjs', plugin_dir_url( __FILE__ ) . 'assets/js/scripts.js' );
}
add_action('wp_enqueue_scripts', 'custom_plugin_enqueue');

I thought your code should work, so I tested it. Specifically, I tested the following:
<?php /*
Plugin Name: Junk
*/
add_action( 'plugins_loaded', array(SMARTPOPUP::getInstance(), 'init') );
class SMARTPOPUP
{
private static $instance = null;
public function init(){
add_action('wp_enqueue_scripts', array($this, 'frontEndAssets'));
}
public function frontEndAssets(){
wp_enqueue_style(
'wpsgdprcss',
plugin_dir_url( __FILE__ ) . 'assets/css/styles.css',
array()
);
wp_enqueue_script(
'wpsgdprjs',
plugin_dir_url( __FILE__ ) . 'assets/js/scripts.js',
array(),
false
);
$localizedata = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'noncesecure' => wp_create_nonce('WP_SMART_GDPR_SLUG'),
);
wp_localize_script( 'wpsgdprjs', 'wpsgdprdata', $localizedata );
}
public static function getInstance(){
if(!isset(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}
This generated the following style and script elements:
<link rel='stylesheet' id='wpsgdprcss-css' href='http://localhost/wp-content/plugins/junk/assets/css/styles.css?ver=4.9.6' type='text/css' media='all' />
<script type='text/javascript'>
/* <![CDATA[ */
var wpsgdprdata = {"ajaxurl":"http:\/\/localhost\/wp-admin\/admin-ajax.php","noncesecure":"8b77af0183"};
/* ]]> */
</script>
<script type='text/javascript' src='http://localhost/wp-content/plugins/junk/assets/js/scripts.js?ver=4.9.6'></script>
The only change I made was I replaced WP_SMART_GDPR_SLUG with 'WP_SMART_GDPR_SLUG' since you probably forgot to include the define for it.
There is nothing wrong with your code itself.
Are you sure that your code is being executed?
I don't think this matters but I am running WordPress Version 4.9.6 using PHP 7.1.17.

Related

WordPress AJAX is_admin is true, causing issues.

i'm trying to make a plugin for WordPress, which is has got an admin section for some basic settings, and also registers some shortcode to display some HTML, which is basically a form.
Here is my main plugin file, plugins/my-plugin/my-plugin.php:
/**
* Plugin Name: Pathway
* Plugin URI: http://www.martynleeball.com/
* Description: Pathway integration.
* Version: 1.0
* Author: Martyn Lee Ball
* Author URI: https://www.martynleeball.com/
**/
define('PATHWAY_VERSION', '0.0.8');
define('PATHWAY_AUTHOR', 'Martyn Lee Ball');
define('PATHWAY__MINIMUM_WP_VERSION', '4.*');
define('PATHWAY_CONTACT', 'martynleeball#gmail.com');
add_action(
'plugins_loaded',
array ( Pathway::get_instance(), 'plugin_setup' )
);
class Pathway
{
protected static $instance = NULL;
public $plugin_url = '';
private $cpt = 'post'; # Adjust the CPT
public function __construct() {}
public static function get_instance()
{
NULL === self::$instance and self::$instance = new self;
return self::$instance;
}
public function plugin_setup()
{
$this->plugin_url = '';
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
// if (is_admin()) {
//
// require_once( $this->plugin_url . 'admin/index.php' );
//
// register_activation_hook( __FILE__, 'install' );
//
// return;
// }
add_shortcode( 'pathway', array($this, 'shortcode'));
add_action( 'wp_ajax_ajax_login', array( $this, 'ajax_login' ) );
add_action( 'wp_ajax_nopriv_ajax_login', array( $this, 'ajax_login' ) );
add_action( 'wp_ajax_ajax_register', array( $this, 'ajax_register' ) );
add_action( 'wp_ajax_nopriv_ajax_register', array( $this, 'ajax_register' ) );
}
public function enqueue()
{
wp_enqueue_script( 'vuejs', 'https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js' );
wp_enqueue_script(
'ajax-handle-form',
"{$this->plugin_url}/wp-content/plugins/pathway/frontend/js/scripts.js"
);
wp_localize_script(
'ajax-handle-form',
'wp_ajax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' )
)
);
}
public function ajax_login()
{
echo 'login';exit;
}
public function ajax_register()
{
echo 'register';exit;
}
public function shortcode()
{
if (!isset($_SESSION['pathway_login'])) {
self::view('forms/login');
}
}
public static function view( $name, array $args = array() ) {
foreach ( $args AS $key => $val ) {
$$key = $val;
}
// $file = $this->plugin_url . 'views/'. $name . '.php';
$file = 'views/'. $name . '.php';
include( $file );
}
}
Please correct me if i'm going wrong somewhere, there's so many mixed guides online showing different ways. Within this file i'm basically:
Adding my scripts and assigning the PHP values.
I would be then starting the admin section however has to comment this out for the AJAX call, this is my issue.
Registering my shortcode.
Adding the actions for the AJAX form submit.
Obviously my issue is that when I hit the is_admin from the AJAX call it is returning true, when it should be false as an public visitor can submit this form. The wp_ajax_nopriv action doesn't appear to work which would solve the issue, this is probably due to me being logged into WordPress.
I have tried logging out of WordPress but the is_admin still returns true!
Can someone advise?
is_admin will return true on all ajax calls.
It is not actually a useful function to check the user as it checks the uri rather than the user details, i.e. if on a admin page = true, if not false.
Now I was a little confused about your question here, it appears you want the is_admin to return false if its actually an ajax call?
if ( is_admin() && ! wp_doing_ajax() ) {}
It will return false on ajax calls.
If you are checking there is an "admin" logged in, as in can edit posts, see the other capabilities here
if ( current_user_can( 'edit_post' ) ) {}
The no_priv hook will not work when logged in, its not called.

I cannot get jQuery to work in wordpress

Tried many different techniques to get jquery working in my custom wordpress theme but still haven't got anywhere.
I've included two different methods that I've tried below near the end of the code, with one commented out here.
Can anyone see why this code might not be working?
PHP:
<?php
function wpb_custom_new_menu() {
register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}
add_action( 'init', 'wpb_custom_new_menu' );
function enqueue_stylesheets() {
wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');
wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Raleway:400,500,600,700');
wp_enqueue_style( 'fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );
}
/*function wp_enqeue_scripts() {
wp_register_script('navbarScroll', home_url() . '/js/navbarScroll.js', array( 'jquery' ));
wp_enqueue_script('navbarScroll');
//wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );
}*/
function navbar_script() {
wp_register_script( 'jquery.navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ) );
wp_enqueue_script( 'jquery.navbarScroll' );
}
add_action('wp_enqueue_scripts', 'enqueue_stylesheets', 'enqueue_scripts', 'navbar_script');
My Test JS (I've used both $ and jquery):
jquery(document).ready(function() {
jquery('#jQueryTest').html('jQuery is Working');
jQuery('nav').hover(function() {
$(this).css('display', 'none');
})
/*var a = $('nav').offset().top;
$(document).scroll(function() {
if ($(this).scrollTop() > a)
{
$(this).removeClass('nav');
$(this).addClass('nav-scrolled');
} else {
$(this).removeClass('nav-scrolled');
}
});*/
});
Well it seems that you have too many parameters in your add_action function.
The add_action should have only 4 arguments as follows:
add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
See WordPress documentation for more information.
That's what should be working just fine:
function enqueueScript() {
wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');
wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Raleway:400,500,600,700');
wp_enqueue_style( 'fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );
wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );
wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );
wp_enqueue_script('navbarScroll');
wp_register_script( 'jquery.navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'jquery.navbarScroll' );
}
add_action( 'wp_enqueue_scripts', 'enqueueScript' );
Note that it is not necessary to enqueue style and script separately. One method can do both by using wp_enqueue_scripts.
If you really want to separate your style and script in different function, you should call add_action this way:
add_action('wp_enqueue_scripts','wp_enqueue_scripts');
add_action( 'wp_enqueue_scripts','enqueue_stylesheets');
add_action( 'wp_enqueue_scripts','enqueue_scripts');
add_action( 'wp_enqueue_scripts','navbar_script');
If you want to load jQuery, add it to your function:
wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js', array(), null, true);
Its easy if you can have a code like this to solve correctly and without confusiong. You have forgotten to pass add_action for your scripts.
function wpb_custom_new_menu() {
register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}
add_action( 'init', 'wpb_custom_new_menu' );
function enqueue_stylesheets() {
//For registering Styles
wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');
wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Montserrat:400,600,700|Raleway:400,500,600,700');
wp_enqueue_style( 'fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );
//For registering Scripts files
wp_enqueue_script( 'jquery');
wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );
wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );
wp_enqueue_script('navbarScroll');
wp_register_script( 'jquery.navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'jquery.navbarScroll' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );
Hope this works for you.
THanks

wp_enqueue_scripts fail to add custom stylesheet

$custom_style = 'css/pre/custom-styles.css';
function custom_stylesheet() {
wp_enqueue_style( 'aps-custom-style', APS_URL .$custom_style, APS_VER );
}
add_action( 'wp_enqueue_scripts', 'custom_stylesheet' );
APS_URL is the url of directory.
You have to pass it to the function:
$custom_style = 'css/pre/custom-styles.css';
function custom_stylesheet($custom_style) {
wp_enqueue_style( 'aps-custom-style', APS_URL .$custom_style, APS_VER );
}
add_action( 'wp_enqueue_scripts', 'custom_stylesheet' );
or declare it global:
$custom_style = 'css/pre/custom-styles.css';
function custom_stylesheet() {
global $custom_style;
wp_enqueue_style( 'aps-custom-style', APS_URL .$custom_style, APS_VER );
}
add_action( 'wp_enqueue_scripts', 'custom_stylesheet' );
wp_enqueue_style( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, string $media = 'all' )
https://developer.wordpress.org/reference/functions/wp_enqueue_style/
You should pass an array as $deps argument first, before $vers argument.

plugin activation hook not working in wordpress

I'm trying to develop my first Wordpress plugin and I got staled in the very first stage. I'm trying to setup some options and database tables when the plugin is activated, but no luck. No matter what I do, the plugin activates, but the database is untouched and the options are not stored in DB. I tried echoing inside the constructor, but it seems that it never reaches it. I have debug activated in WP, but no error is being reported. The function is not being hooked. Does someone can spot what's wrong with my code?
Thanks for any help in advance.
class Myplugin {
private static $instance;
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
register_activation_hook( __FILE__, array( &$this, 'plugin_activate' ) );
}
public function plugin_activate() {
if ( version_compare( get_bloginfo( 'version' ), '3.8.2', ' < ' ) ) {
deactivate_plugins( basename( __FILE__ ) );
} else {
$rlm_rsvplus_options = array(
'db_version' => '1.0',
'event_name' => '',
'end_date' => '',
);
update_option( 'rlm_myplugin_options', $rlm_myplugin_options );
require_once( "includes/rlm_myplugin_db_setup.php" );//It never reaches this file.
}
}
}
$myplugin = Myplugin::get_instance();
Back to the WordPress documentation.
<?php register_activation_hook( $file, $function ); ?>
Parameters
$file
(string) (required) Path to the main plugin file inside the wp-content/plugins directory. A full path will work.
Default: None
$function
(callback) (required) The function to be run when the plugin is activated. Any of PHP's callback pseudo-types will work.
Default: None
Possible issue
If calling a function from a file that is outside of main plugin file, then the hook will not work as it is not pointing to the right file. FILE will point to the file where the code is written. So if you happen to include this part of code from elsewhere (another file - not the main plugin file) it's not supposed to work unless you point the right path.
Solution
A solution could be declaring a constant in the main plugin file.
your_main_plugin_file.php
define(PLUGIN_FILE_URL, __FILE__);
and then use it in your included file like so.
includes/some_file.php
<?php register_activation_hook( PLUGIN_FILE_URL, ['your_class_name_here', 'your_class_method_name_here']); ?>
or if you use functions instead of classes then do
<?php register_activation_hook( PLUGIN_FILE_URL, 'your_function_name_here'); ?>
The register_activation_hook call needs to be outside of the class itself.
Something like:
class Myplugin {
private static $instance;
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// do other stuff here
}
public function plugin_activate() {
if ( version_compare( get_bloginfo( 'version' ), '3.8.2', ' < ' ) ) {
deactivate_plugins( basename( __FILE__ ) );
} else {
$rlm_rsvplus_options = array(
'db_version' => '1.0',
'event_name' => '',
'end_date' => '',
);
update_option( 'rlm_myplugin_options', $rlm_myplugin_options );
require_once( "includes/rlm_myplugin_db_setup.php" );
}
}
register_activation_hook( __FILE__, array( 'Myplugin', 'plugin_activate' ) );
You can read more on the following tutorial by Francis Yaconiello about How to write WordPress plugin.
In order to work register_activation_hook OR register_deactivation_hook the functions should be in index file OR we need to specify the full path to the file argument.
Replace this:
register_activation_hook( FILE, array( &$this, 'plugin_activate' ) );
With:
register_activation_hook( FILE . 'plugin-main-file.php', array( &$this, 'plugin_activate' ) );
Here the point is register_activation_hook( $file, $function );
Here $file means Path to the main plugin file
Reference: https://codex.wordpress.org/Function_Reference/register_activation_hook
Thanks,
- Adi

add jquery file if a certain page is included

I was wondering if anyone could help me by explaining if it is possible to enqueue a javascript file only if for example homepage.php is included.
what i have tried to do inside homepage.php:
class homepage_js {
static $add_script;
static function init() {
add_action('init', array(__CLASS__, 'register_script'));
add_action('wp_footer', array(__CLASS__, 'print_script'));
}
static function register_script() {
wp_register_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true);
}
static function print_script() {
if ( ! self::$add_script )
return;
wp_print_scripts('my-script');
}
}
homepage_js::init();
Thanks in advance for help.
If this is for your wordpress home page you can do this in functions.php
add_action( 'wp_enqueue_scripts' , my_enqueue_scripts );
function my_enqueue_scripts(){
if ( is_home() ) {
wp_enqueue_script( ... );
}
}

Categories