add jquery file if a certain page is included - php

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( ... );
}
}

Related

register_activation_hook is not working - Wordpress

I'm trying to create a plugin for shortcodes. But my activation hook is not working. Plugin is activated in my wp-admin/plugins page but nothing works which is in my code like:
My enqueue & shortcode functions are not working. I've tried plugin_dir_path(__FILE__) & plugin_dir_url(__FILE__) b ut nothing works.
Here is my code:
if (!class_exists( 'DiliviBlocks' )) {
class DiliviBlocks {
public function __construct() {
$this->setup_actions();
$this->plugin_dir = plugin_dir_path(__FILE__);
}
/**
* Setting up Hooks
*/
public function setup_actions() {
register_activation_hook( plugin_dir_path(__FILE__), array( $this, 'activate_plugin' ) );
}
/**
* Activate callback
*/
public function activate_plugin() {
add_action( 'wp_enqueue_scripts', array($this, 'dilivi_blocks_scripts') );
add_shortcode( 'vans_search_form', array($this, 'vans_search_form_shortcode') );
}
public function dilivi_blocks_scripts() {
wp_enqueue_style( 'dilivi-blocks-plugin-css', plugin_dir_path(__FILE__) . '/assets/css/styles.css');
wp_enqueue_script( 'dilivi-blocks-plugin-jquery', plugin_dir_path(__FILE__) . '/assets/js/jquery.js' );
wp_enqueue_script( 'dilivi-blocks-plugin-js', plugin_dir_path(__FILE__) . '/assets/js/scripts.js' );
}
public function vans_search_form_shortcode($atts) {
return 'Hello World';
}
}
$diliviBlocks = new DiliviBlocks();
}
Please help me. I'm stuck
The documentation states that you only need the plugin directory name, and the name of the initial file. You should not include the whole path to it.
If your plugin contains only the file, than just __FILE__ would suffice.
In your case, it will probably be something like dilivi-blocks/divili-blocks.php.
Also, be aware that functions will only be executed once -- when your plugin is activated. If it is already active, the functions will not execute.
You should know that enqueueing stylesheets and the like will have to be done every time a page loads, so binding them to a single-use hook will not work. The wp_enqueue_scripts hook should be used for that.

Is there any alternative way to enqueue scripts in wordpress?

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.

wordpress: how to set up a custom URL AJAX API

I'm trying to implement a custom JSON API upon Wordpress, like /api3/get_posts, I refer to the implementation of plugin JSON-API, but it just doesn't work. Below is my code:
$myPluginBase = 'api3';
function my_plugin_init() {
global $wp_rewrite;
add_filter('rewrite_rules_array', 'my_plugin_rewrites');
add_action('template_redirect', 'my_plugin_template_rewrite');
$wp_rewrite->flush_rules();
}
function my_plugin_template_rewrite(){
global $myPluginBase;
if( isset( $_REQUEST[ $myPluginBase ] ) ){
echo $_REQUEST[ $myPluginBase ];
exit;
}
}
function my_plugin_activation() {
// Add the rewrite rule on activation
global $wp_rewrite;
add_filter('rewrite_rules_array', 'my_plugin_rewrites');
$wp_rewrite->flush_rules();
}
function my_plugin_deactivation() {
// Remove the rewrite rule on deactivation
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function my_plugin_rewrites($wp_rules) {
global $myPluginBase;
if (empty($base)) {
return $wp_rules;
}
$my_plugin_rules = array(
"$myPluginBase\$" => "index.php?{$myPluginBase}=info",
"$myPluginBase/(.+)\$" => "index.php?{$myPluginBase}=\$matches[1]"
);
return array_merge($my_plugin_rules, $wp_rules);
}
// Add initialization and activation hooks
add_action('init', 'my_plugin_init');
register_activation_hook( __FILE__, 'my_plugin_activation');
register_deactivation_hook( __FILE__, 'my_plugin_deactivation');
It seems like the template_redirect action works, as I open /api3=hello, the server will send hello back. But if I try to open /api3/hello, it keeps showing me the home page.

WORDPRESS add_filter('cron_schedules', ...) not working in a PHP class

I tried to declare a new time interval for a WP_CRON.
When I do it in a PHP file it works.
When I do it in a PHP Class it doesn't.
Can someone see what I'm doing wrong ?
I'm using the plugin cron view to check if the declaration is working or not.
If I solve this problem I think it will also solve my problem to know why my cron job is not triggered in the class but works properly when not in a class.
=> File myplugin.php
function set_up_option_page() {
add_options_page( [...]);
}
add_action( 'admin_menu', 'set_up_option_page' );
function do_some_rock() {
$instance = My_Plugin_Class::instance();
if ( isset($_POST['action']) && 'do-magic' == $_POST['action'] ) {
$instance->do_stuff();
}else{
// Display the form.
<?
}
}
=> File My_Plugin_Class.php
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class My_Plugin_Class {
private static $_instance = null;
public function __construct () {
[...]
add_filter( 'cron_schedules', array($this,'cron_time_intervals'));
}
public function cron_time_intervals( $schedules ) {
echo "——— cron time intervals —— ";
$schedules['minutes_1'] = array(
'interval' => 10*60,
'display' => 'Once 10 minutes'
);
return $schedules;
}
public static function instance () {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
} // End instance ()
Best regards.
I am almost sure that do_some_rock() is not called every time - only when someone goes to that page. You can move add_filter( 'cron_schedules', array($this,'cron_time_intervals')); from your class constructor to main plugin file myplugin.php and do more or less something like this
add_action( 'admin_menu', 'set_up_option_page' );
$instance = My_Plugin_Class::instance();
add_filter( 'cron_schedules', array($instance ,'cron_time_intervals'));
One extra question. Does My_Plugin_Class constructor contain any code you would like to prevent being executed during each request?
I think the proper way to do this, is to have a specific class for my Cron.
This class is instanciated on each request this is why the code shouldn't be in a class with a static instance as I did before.
Also I think it's better to have the Cron outside the plugin class for logic and cleaner code purpose. Thanks to Lukas Pawlik for the help.
if (!defined('ABSPATH')) exit;
new My_Cron();
class My_Cron {
public function __construct() {
add_filter('cron_schedules', array($this, 'cron_time_intervals'));
add_action( 'wp', array($this, 'cron_scheduler'));
add_action( 'cast_my_spell', array( $this, 'auto_spell_cast' ) );
}
public function cron_time_intervals($schedules)
{
$schedules['minutes_10'] = array(
'interval' => 10 * 60,
'display' => 'Once 10 minutes'
);
return $schedules;
}
function cron_scheduler() {
if ( ! wp_next_scheduled( 'cast_my_spell' ) ) {
wp_schedule_event( time(), 'minutes_10', 'cast_my_spell');
}
}
function auto_spell_cast(){
My_Plugin_Class::instance()->launch_spell();
}
}
I am not Sure But Try this.
add_filter( 'cron_schedules', array($this,'cron_time_intervals'),1);
And Check cron_time_intervals() Function is Call or Not.

Run JS only on pages with my widget

I'm trying to get a widget to only load javascript on a page where the widget is present.
I've tried adding the add action in the 'showWidget' didn't work.
What am I doing wrong?
PHP
wp_register_sidebar_widget('MyWidget','MyWidget', 'showWidget');
add_action('wp_enqueue_scripts', 'addScript'); //now the script appears on every page
function addScript()
{
wp_register_script('MyWidgetJs', plugins_url( '/script.js' , __FILE__), array('jquery'));
wp_enqueue_script('MyWidgetJs');
}
function showWidget($args)
{
// add_action('wp_enqueue_scripts', 'addScript'); //I tried this but it doesn't work :(
wp_enqueue_script('MyWidgetJs');
extract($args);
/* do widget stuff */
}
Seems that the new version of WordPress supports this: http://codex.wordpress.org/Version_3.3
Register your script, but don't enqueue it. In your widget PHP, add in the wp_enqueue_script('your_script_name'); and it'll load it only when your widget is used and place it in the footer.
You are going to upgrade to 3.3, right? :)
SO, something like this should work just fine:
wp_register_sidebar_widget('MyWidget','MyWidget', 'showWidget');
function showWidget($args) {
wp_enqueue_script('MyWidgetJs');
extract($args);
/* do widget stuff */
}
You want to use is_active_widget() conditional to do something like:
<?php
if ( is_active_widget('MyWidget') ) {
add_action('wp_enqueue_scripts', 'addScript');
}
?>
using your above code the final widget may look like:
<?php
if ( is_active_widget('MyWidget') ) {
add_action('wp_enqueue_scripts', 'addScript');
}
function addScript()
{
wp_register_script('MyWidgetJs', plugins_url( '/script.js' , __FILE__), array('jquery'));
wp_enqueue_script('MyWidgetJs');
}
function showWidget($args)
{
wp_enqueue_script('MyWidgetJs');
extract($args);
/* do widget stuff */
}

Categories