wp_enqueue_script includes plugin directory too soon in filepath - css

public function setup(){
//...
add_action( 'wp_enqueue_scripts', array( $this, 'register_plugin_styles' ) );
}
function register_plugin_styles(){
wp_register_style( 'dontwaste', JSC_DONT_WASTE . '/styles/dontwaste_styles.css' );
wp_enqueue_style( 'dontwaste', false, null, null );
}
The JSC_DONT_WASTE is the path to the plugin directory, so JSC_DONT_WASTE . '/styles/dontwaste_styles.css' returns the following:
/Applications/AMPPS/www/wpplugin/wp-content/plugins/dontwaste/styles/dontwaste_styles.css
and this is exactly the path I need to reach my css file.
But the code above returns this NOT FOUND error:
http://127.0.0.1/wpplugin/Applications/AMPPS/www/wpplugin/wp-content/plugins/dontwaste/styles/dontwaste_styles.css?ver=4.6.1 404 (Not Found)
You'll notice in the beginning there's a /wpplugin/ (the name of the plugin folder) right after the localhost. How do I get rid of that and get the path to work?
There's also the version number which even though I've set to NULL it still sets a version number.

Yes, that makes sense.
Javascript and CSS assets are loaded using their URI (or URL) and not path on the server directories. As they're loaded on the frontend side. So it'll be something like yoursite.com/wp-content/plugins/your-plugin/js/your-asset.js
So you can't use :
plugin_dir_path( __FILE__ )
You must use :
plugin_dir_url( __FILE__ )
The first one is for files loaded in your plugin files (server side). Like a require_once. And the second one if for assets loaded on the user side.
Therefore, you can do something like :
// For the files called in your php :
if ( ! defined( 'PLUGIN_DIR' ) ) {
define( 'PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}
// For the assets files loaded on the client side :
if ( ! defined( 'PLUGIN_ASSETS_URL' ) ) {
define( 'PLUGIN_ASSETS_URL', plugin_dir_url( __FILE__ ).'/assets' );
}

Related

Localize WooCommerce Extension

I am developing WC extension by its new way. Everything works like a charm instead of localization. I have generated JSON by wp i18n make-json and using in index.js like this:
import { __ } from '#wordpress/i18n';
__( 'Verify licence', 'domain' );
Unfortunatelly the strings are never been translated. Should I load the JSON myself or register the script wp_set_script_translations( 'domain-script', 'domain', plugin_dir_path( __FILE__ ) . '/languages' );
?
At server side translations work. I am really confused about the JS translation flow. Thanks for any help.
For future generations the solution is simple.
You have to call something like this:
public function extension_set_script_translations() {
$loaded = wp_set_script_translations( 'extension', 'extension', plugin_dir_path( __FILE__ ) . '/languages' );
}
private function initLocalizations() {
add_action( 'admin_enqueue_scripts', [$this, 'extension_set_script_translations'] );
}
Another important thing is name of the language JSON file.
{text-domain}-{locale}-{script-handle}.json

plugin_dir_url( __FILE__ ) not working in my wordpress plugin development

This is my plugin directory access when I use plugin_dir_url(__FILE__)
http://127.0.0.1/WordPressProject/myplugin/wp-content/plugins/advanced-plugin/admin/
But I want to access to http://127.0.0.1/WordPressProject/myplugin/wp-content/plugins/advanced-plugin/
After using the function it includes with
admin
folder. not the base plugin base url
Thanks
Use plugin_dir_url( __FILE__ ); for the URL and plugin_dir_path( __FILE__ ); for the path.
Pass the plugin’s main file to both functions to get similar results.
plugins_url( string $path = '', string $plugin = '' )
Retrieves a URL within the plugins or mu-plugins directory.
For more information
Thanks
Finally I got a solution by using
plugin_dir_url(dirname(FILE))

How to make Gutenberg Block Translation work?

I've just built a Gutenberg block, and I'd like to have it translated into different languages. I am using my WordPress in Portuguese and I've made a Portuguese translation. I followed all the steps available in the documentation https://developer.wordpress.org/block-editor/developers/internationalization/ and it still didn't work.
My plugin is called spoiler-alert.
I have created a .pot file named spoileralert.pot in the /spoiler-alert/languages folder. Then, I've generated the md5 files and even created a new file with all my strings using a script handler. My languages folder structure looks like this:
languages
- spoileralert.pot
- spoileralert-pt_BR.po
- spoileralert-pt_BR-<HASH-CODE-1>.json
- spoileralert-pt_BR-<HASH-CODE-2>.json
- spoileralert-pt_BR-<HASH-CODE-3>.json
- spoileralert-pt_BR-spoileralert.json
And here is my PHP file spoiler-alert.php:
function spoiler_alert_spoiler_alert_block_init() {
$dir = dirname( __FILE__ );
$script_asset_path = "$dir/build/index.asset.php";
if ( ! file_exists( $script_asset_path ) ) {
throw new Error(
'You need to run `npm start` or `npm run build` for the "spoiler-alert/spoiler-alert" block first.'
);
}
$index_js = 'build/index.js';
$script_asset = require( $script_asset_path );
wp_register_script(
'spoiler-alert-spoiler-alert-block-editor',
plugins_url( $index_js, __FILE__ ),
$script_asset['dependencies'],
$script_asset['version']
);
$editor_css = 'build/index.css';
wp_register_style(
'spoiler-alert-spoiler-alert-block-editor',
plugins_url( $editor_css, __FILE__ ),
array(),
filemtime( "$dir/$editor_css" )
);
$style_css = 'build/style-index.css';
wp_register_style(
'spoiler-alert-spoiler-alert-block',
plugins_url( $style_css, __FILE__ ),
array(),
filemtime( "$dir/$style_css" )
);
register_block_type( 'spoiler-alert/spoiler-alert', array(
'editor_script' => 'spoiler-alert-spoiler-alert-block-editor',
'editor_style' => 'spoiler-alert-spoiler-alert-block-editor',
'style' => 'spoiler-alert-spoiler-alert-block',
) );
wp_set_script_translations( 'spoileralert', 'spoiler-alert', plugin_dir_path( __FILE__ ) . '/languages' );
}
add_action( 'init', 'spoiler_alert_spoiler_alert_block_init' );
In my .js files I've imported the translation package using: import { __ } from '#wordpress/i18n';
And I am using the translations like: title: __( 'Spoiler Alert', 'spoiler-alert' ),
How can I make the translation display correctly?
It's been a while already, but it might still be useful to you or someone else out there. I'm simply copying and pasting what I've already answered here.
I've been through this process quite a few times already, so I'm 100% sure this is working properly. Carefully go through each one of the steps and you should manage to solve any issues you might be running into ;)
Translation has finally been properly developed and documented: https://developer.wordpress.org/block-editor/developers/internationalization/
Basically, you need to:
Use the wp-i18n package to define which are the strings in your project to be translatable.
Compile your code (wp i18n make-pot will search for translation strings in your compiled code, not in your source).
Use the WP-CLI (wp i18n make-pot) to create a .pot file, just like we've always used with WP themes and plugins.
Generate a .po file based on our previously created .pot and translate its content.
Use the WP-CLI again (wp i18n make-json) to convert our .po file to the JSON format needed.
Use the wp_set_script_translations PHP function to load the translation files.

Wordpress: Load specific CSS for admin user

I want to work on my style.css file.
But It would be better if after all change and test I publish it for users.
So Is there any way to make another style.css which load just for admin user?
You need to check the logged in user role before queuing it.
So the code should be like bellow.
you need to replace the plugins_url( 'my-plugin/css/plugin.css' ) with your stylesheet's path
function register_only_for_admin_styles() {
if( current_user_can('editor') || current_user_can('administrator') ) {
wp_register_style( 'admin-style', plugins_url( 'my-plugin/css/plugin.css' ) );
wp_enqueue_style( 'admin-style' );
}
}
add_action( 'wp_enqueue_scripts', 'register_only_for_admin_styles' );
Try the code then let me know the result.
Thanks

Why is my javascript file not found by wordpress? and why doesn't my javascript file refresh?

I added custom javascript to a wordpress theme through the wp_enqueue_script()
function.
I placed my file in theme-folder/js/my-javascript.js
But it would not be found by wordpress! I would see the script tag in the html source inserted by wordpress, but clicking on it would take me to a "not found page". I looked around everywhere to see if this was some caching issue. Turned off caching, still nothing.
Finally, I ended up placing my-javascript.js file in the root of theme-folder, instead of 'js' folder. And now my js file was being found and loading.
But now a new problem I don't understand.. I would edit my file and the changes wouldn't reflect! I would have to change the file name of my js file everytime I made a change, renaming the file in my enqueue script function as well...I just wanted to get this task done.
So why does this happen? The site is hosted on dreamhost, and I suspect they used a one-click installer. Does dreamhost do some sort of caching on its own? and that's why?
Am I dumb? or does wordpress somehow know that I hate it?
Edit:
This is how I'm loading the script and how I left it working, but why won't my script refresh when I make changes and why doesn't it work when I place it in theme's 'js' folder?
/* Add floater script */
function add_floater_div_script(){
/* wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true); */
if ( is_page(1208) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), '', true);
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
Edit: Changed code from "array ( " to "array(" because someone thought this was a problem. I did a quick check myself and PHP is ok with this space so this does not explain the weird wordpress behaviour I'm trying to solve.
Yeah, caching gets really annoying, Though hard reloading should solve the prob but we can't expect client to do it everytime. And WordPress has added a way to take care of that :)
wp_enqueue_script accepts 4th parameter as version number...
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
So just update version after each update...
For development, Just set it as time()... So that it is reloaded every single time and never cached...
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), time(), true);
Your code will look something like this...
/* Add floater script */
function add_floater_div_script(){
/* wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true); */
if ( is_page(1208) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array('jquery'), time(), true);
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
BE SURE TO REMOVE time() FROM PRODUCTION VERSION.
Or your file will never be cached by browser... Just set the version of your theme after dev is complete, so that every new version gets JS updated.
Try by wrapping your enqueue action in a function that you'll call on after_setup_theme hook in your functions.php
<?php
add_action( 'after_setup_theme', 'yourtheme_theme_setup' );
if ( ! function_exists( 'yourtheme_theme_setup' ) ) {
function yourtheme_theme_setup() {
add_action( 'wp_enqueue_scripts', 'yourtheme_scripts' );
}
}
if ( ! function_exists( 'yourtheme_scripts' ) ) {
function yourtheme_scripts() {
if ( is_page( 1208 ) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array( 'jquery' ), '', true );
}
}
}
Also be sure you're on page with id of 1208 to see if the script is actually loaded (because of the conditional).
And do a hard refresh (Ctrl+Shift+R).
The most common issue I see is an error in how you're enqueueing the file. Can you post code in your functions.php file that's enqueuing the JS file? Always be sure to reference the codex and other developer materials as well: https://developer.wordpress.org/themes/basics/including-css-javascript/
For future reference, it should look something like this:
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/my-javascript.js');
Edit: After OP posted their code I saw they have a space after array which is causing an error, here is the correct code:
function add_floater_div_script() {
if ( is_page( 1208 ) ) {
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js', array( 'jquery' ), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'add_floater_div_script' );
add_action('wp_enqueue_scripts', 'load_scripts', 12);
function load_scripts() {
wp_enqueue_script('filename', get_template_directory_uri() . '/js/filename.js', array(), '1.0.0', true );
}
This is the proper way to import js in wordpress..
An really easy way to prevent caching of loaded resource files like Javascript-files is to add an random value after the filename that is to be included like so:
wp_enqueue_script( 'custom-floater', get_template_directory_uri() . '/custom-floater-8.js' . '?' . rand(), array('jquery'), '', true);
The PHP function
rand()
generates a random number and is appended to the file name after a '?' as query string. This forces reloading of the file every time the webpage is loaded.
Of course dismiss it for the production version.
Sometimes the issue could be simple somewhere a duplicated declaration of the name of the enqueue_script.
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/custom-floater-
8.js', array('jquery'), '', true);
...
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/custom-floater-
8.js', array('jquery'), '', true);
Don't use twice the same name 'custom-script' for example. The second will not be loaded.

Resources