How to enqueue scripts in my plugin - php

I need to use JavaScript (JQuery) within my plugin. The enqueueing should not be inside the themes' function.php. Imagine telling your users "Please to add this line of code in your functions.php etc..."
/plugins/foo-plugin/foo-plugin.php:
<?php
/**
* Plugin Name: Foo Plugin
* Plugin URI: foobar.com
* Description: ___DEV___
* Version: 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) exit;
function Foo_Plugin() {
return Foo_Plugin::instance();
} // End Foo_Plugin()
add_action( 'plugins_loaded', 'Foo_Plugin' );
/**
* Load Scrips
*/
function enqueue_js() {
// JS
wp_enqueue_script( 'foo', './assets/js/foo.js', false );
}
add_action('wp_enqueue_scripts', 'enqueue_js');
[...]
I've followed this but I'm not getting my output:
//foo.js:
$(document).ready(function(){
console.log("foo is ready")
})
I have deactivated/reactivated the plugin and nothing. How to use JS/CSS in my plugin? As you've guested, it's my first time creating one ;)
Path to JS:
/plugins/foo-plugin/assets/js/foo.js

In the admin section, use the admin_enqueue_scripts action hook.
function enqueue_js() {
wp_enqueue_script( 'foo', './assets/js/foo.js');
}
add_action('admin_enqueue_scripts', 'enqueue_js');
Also, don't put that false in there. The default should be an empty array if there are no dependencies.

Related

Wordpress: Get pll_the_languages inside my plugin

How can i get languages into my custom plugin of wordpress?
When i call pll_the_languages() it's output me error.
Maybe i should call some global method?
My plugin code:
/**
* woocommerce-admin-ajax
*
* #package woocommerce-admin-ajax
* #author Sergey Samokhvalov
* #wordpress-plugin
*
* Plugin Name: WooCommerce Admin Ajax
* Plugin URI: https://redirex.studio
* Description: Additional functionality for ajax update of product in admin page without reload page.
* Version: 1.0
* Requires PHP: 5.6.20
* Author: Sergey Samokhvalov
* Author URI: https://github.com/RedirexStudio/woocommerce-admin-ajax
* Text Domain: Woocommerce Admin Ajax
*/
/* Registrate admin js and styles */
add_action( 'admin_enqueue_scripts', 'reg_amin_js' );
function reg_amin_js( $page ) {
// change to the $page where you want to enqueue the script
if( $page == 'post-new.php' || $page == 'post.php' || $page == 'edit.php' ) {
// Enqueue WordPress media scripts
wp_enqueue_media();
// Enqueue custom script that will interact with wp.media
wp_enqueue_script( 'woocommerce_admin-scripts', plugins_url('/admin/js/admin.js',__FILE__ ), array('jquery') );
// Enqueue custom styles for admin panel
wp_enqueue_style('woocommerce_admin-styles', plugins_url('/admin/css/style.css', __FILE__ ));
}
}
/* //END//Registrate admin js and styles */
/* Polylang capability */
pll_the_languages();
/* //END//Polylang capability */
My issue is solved.
You should use admin_init action:
function plugin_pll_register_string() {
if ( function_exists( 'pll_register_string' ) ) {
pll_register_string('woocommerce-admin-ajax-strings', 'Update');
pll_register_string('woocommerce-admin-ajax-strings', 'Published');
pll_register_string('woocommerce-admin-ajax-strings', 'Product is updated!');
}
}
add_action( 'admin_init', 'plugin_pll_register_string' );

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.

My WordPress plugin wp_enqueue_scripts won't work

I am working on the following code. I have looked at all the documents regarding wp_enqueue_scripts and wp_register_script I cannot get it my Wp_callApi.js to load.
How can I fix this?
<?php
/*
Plugin name: My webservice
Version: 1.4
Description: Calling Webservice with javascript.
Auther: JellyDevelopment
Author URI: http://jellydevelopments.co.za
Plugin URI: http://jellydevelopments.co.za
*/
add_action( 'wp_enqueue_scripts', 'load_Javascript' );
function load_Javascript() {
wp_register_script('prefix_script_01', plugins_url( 'Wp_callApi.js', __FILE__ ), array ('jquery'), "2.1", true );
}
//add_action( 'wp_enqueue_scripts', 'addMy_script' );
function addMy_script() {
wp_enqueue_scripts( 'Wp_callApi' );
}
add_action( 'woocommerce_payment_complete', 'addMy_script', 10, 1 );
?>
You have mutliple errors here. Try this version.
<?php
/*
Plugin name: My webservice
Version: 1.4
Description: Calling Webservice with javascript.
Auther: JellyDevelopment
Author URI: http://jellydevelopments.co.za
Plugin URI: http://jellydevelopments.co.za
*/
function load_Javascript()
{
wp_enqueue_script( 'prefix_script_01', plugins_url( '/Wp_callApi.js', __FILE__ ), array('jquery') );
}
add_action( 'wp_enqueue_scripts', 'load_Javascript' );
?>
This will precisely do what you want. It will enqueue a file named Wp_callApi.js to your front end. This file must be residing at the root of this plugin that you write. If you want to add this file to wordpress admin dashboard then you need to change the action. The last line will change to.
add_action( 'admin_enqueue_scripts', 'load_Javascript' );

Developing Wordpress-Plugin: Problems with loading .js into head and HTML-Snippet as a Shortcode

I was asked to develope a Wordpress plugin for a project I am currently involved in, since I normally do Graphics and UX Design (CSS3). I am not that familiar with developing plugins for WP, although I've got quite some understanding of PHP. I've got the following code:
<?php
/**
* Plugin Name: ExpButton Wordpress Plugin
* Plugin URI: https://url.de
* Description: Ein Generator des Expbuttons
* Version: 0.1
* Author: Wilko Meyer
* Author URI: http://url.com
**/
/**
* Loading js into header
**/
function add_async($url)
{
if (strpos($url, '#asyncload')===false)
return $url;
else if (is_admin())
return str_replace('#asyncload', '', $url);
else
return str_replace('#asyncload', '', $url)."' async='async";
}
add_filter('clean_url', 'add_async', 11, 1);
function expertbuttonjs()
{
// Loading the JS
wp_register_script( 'custom-script', plugins_url( 'https://www.expert-button.de/js.js#asyncload', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), '20120208', true );
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_the_lot' );
/**
*Creating Shortcode
**/
add_shortcode( 'shortcode', 'expbutton' );
function expbutton( $atts ) {
/* Turn on buffering */
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_bl$
<?php
/* Get the buffered content into a var */
$sc = ob_get_contents();
/**
*Expbutton to Shortcode
**/
add_shortcode( 'shortcode', 'expertbutton' );
function expertbutton( $atts ) {
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_bl$
<?php
$sc = ob_get_contents();
ob_end_clean();
/* Return the content as usual */
return $sc;
}
?>
The purpose of this plugin is to load the js.js as async into the of the page and to create an shortcode from the HTML Code below the /* Turn on buffering */ section which can be used at wordpress sites.
Currently the code does not load the js into header and the shortcode which should be created does not work either and I have no Idea why. Hope someone can help me with this problem & has some clue.
Why the plugin doesn't work?
Thanks in advance.
I have made some important littles changes. The html code of your buttons is incomplete (so I have try to guess). The name ou your javascript file seems to me very strange and unusual...
<?php
/**
* Plugin Name: ExpButton Wordpress Plugin
* Plugin URI: https://url.de
* Description: Ein Generator des Expbuttons
* Version: 0.1
* Author: Wilko Meyer
* Author URI: http://url.com
**/
/**
* Loading js into header
**/
function add_async($url)
{
if ( strpos($url, '#asyncload') === false )
return $url;
else if ( is_admin() )
return str_replace('#asyncload', '', $url);
else
return str_replace('#asyncload', '', $url)."' async='async";
}
add_filter('clean_url', 'add_async', 11, 1);
There was a problem in the url in wp_register_script() function that I have corrected and in the add_action() too: your javascript file has to be inside your plugin root folder (I mean not in a subfolder). Also your JS file name seems to me very strange (normally it's file finishing with .js extension and not with .js#asyncload):
function expertbuttonjs()
{
// Loading the JS
wp_register_script( 'custom-script', plugins_url('/js.js#asyncload', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), '20120208', true );
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'expertbuttonjs' );
Dont use shortcode name for shortcodes functions. The code of your buttons are incomplete in your code. Also you can't have 2 times the same name for shortcodes or functions:
/*
* expbutton Shortcodes
*/
add_shortcode( 'expbutton', 'expbutton' );
function expbutton( $atts ) {
/* Turn on buffering */
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_blank" href="'.$sc.'">Text Button</a><div>
<?php
/* Get the buffered content into a var */
$sc = ob_get_contents();
/*
* expertbutton Shortcode
*/
add_shortcode( 'expertbutton', 'expertbutton' );
function expertbutton( $atts ) {
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_blank" href="'.$sc.'">Text Button</a><div>
<?php
$sc = ob_get_contents();
ob_end_clean();
/* Return the content as usual */
return $sc;
}
?>
This should work now.

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