Wordpress: How can I pick plugins directory in my javascript file? - wordpress

I need to access plugins directory in my customer javascript file. I know we have do have functions to retrieve plugins directory path using php function plugins_url().
However, I need this to retrieve in my js file where I have to put some images.
Any ideas??
PS: My js file is saved as a javascript file and therefore, I can't use php tags in it

Use <?php echo plugins_url(); ?> where you want to get the url in the js file.
For example:
var pluginUrl = '<?php echo plugins_url(); ?>' ;

It's actually quite easy...
In functions.php
wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main.js', array('jquery'), '20151215', true );
$translation_array = array( 'templateUrl' =>get_stylesheet_directory_uri() ); //after wp_enqueue_script
wp_localize_script( 'main', 'jsVars', $translation_array );
then in the js-file:
var sitepath=jsVars.templateUrl+"/";
Edit: Just in case it's not understood completely:
The translation array is created and contains a key value pair
The array is then injected as jsVars (javascript variable) into the js scripts
So basically we (mis)use the translation array to inject variables to JS
with the wp_localize_script command.
off course instead of the templateUrl you can define all the params you want with PHP to inject their values into any js file you want.
In this example we inject the template Url into the main js script via jsVars, but it can be any variable into any js script

I've got the result just by assigning the real plugin url:
let pluginUrl = "../wp-content/plugins/YOUR_PLUGIN_FOLDER_NAME/";

Related

Passing data from php to JavaScript for Gutenberg Block with editor Script registered via block.json

I am building a custom Gutenberg block an register the editor script as recommended in the block.json file.
"editorScript": "file:./index.js",
Now I would like to pass data from php to Javascript using the wp_add_inline_script() function. However this requires the handle of the script. In the block.json I don't name a handle and there doesn't seem to be a possibility to do it.
Is there something like a default handle? Or is there another way to pass data from my php plugin file to JavaScript (I want to pass the plugin directory path).
Any help is highly appreciated!
Yes, wp_add_inline_script() is used for passing data from PHP to JavaScript, including Gutenberg blocks.
The script handle you are looking for is the name of your block with the / replaced with a -, eg:
block.json
{
"name": "my/blockname",
"editorScript": "file:./index.js",
...
}
my-block.php
function my_blockname_add_inline_script()
{
// Plugin path for my block
$path = plugin_dir_url(__FILE__);
$handle = 'my-blockname'; // name from block.json with a '-' instead of '/'
$data = 'const myBlockPath ="' . $path . '";';
$position = 'before';
wp_add_inline_script($handle, $data, $position);
}
/**
* Registers the block using the metadata loaded from the `block.json` file.
*/
function my_blockname_block_init() {
register_block_type( __DIR__ . '/build' );
// Enqueue script after register_block_type() so script handle is valid
add_action('admin_enqueue_scripts', 'my_blockname_add_inline_script');
add_action('wp_enqueue_scripts', 'my_blockname_add_inline_script');
}
add_action( 'init', 'my_blockname_block_init' );

wp_enqueue_script only on certain page templates

I am doing this in a plugin. I have the following in an attempt to only enqueue a script when my template file archive-my_custom_post_type.php is used.
add_action('wp_enqueue_scripts', 'my_enqueue');
function my_enqueue($hook) {
if(is_page_template('archive-my_custom_post_type')){
wp_enqueue_script( 'ajax-scripts', plugins_url( '/js/myjquery.js', __FILE__ ), array('jquery') );
}
}
It is not working. It does not load the jquery file on ANY front-end pages, let alone when archive-my_custom_post_type.php is rendered. However, when I remove that if conditional, it loads on ALL my front-end pages.
Question: How can I do a conditional enqueue of a script whenever my custom post type archive template is being used?
You need to use the complete file name, including .php. So in your case you will need to use:
is_page_template('archive-my_custom_post_type.php')
Also, if your template is under a subdirectory you will need to specify that as well.
Ref: https://developer.wordpress.org/reference/functions/is_page_template/#more-information
If you're using is_page_template function, you should also use as parameter the full path (including subdirectories) for the template. For example, if your template is located in your-theme-directory/templates/template-file.php then you should use it like this:
if(is_page_template('templates/template-file.php')){
wp_enqueue_script( 'ajax-scripts', plugins_url( '/js/myjquery.js', __FILE__ ), array('jquery') );
}

Wordpress: How to insert javascript code (without referencing an external asset) using the API?

Using wp_enqueue_script() I can add references to extenal .js assets, but I want to insert the actual javascript code inside <script> tags.
My limitation is that I can't add it directly to, for example, the head.php file because it's a user-configurable bit of javascript, so I want to read it from the theme options and insert it programmatically.
Is it possible to do this using the API?
You can use the head hook and then just echo out the JS as a string using PHP, like so;
<?php
function addUserScript() {
$userScript = '<script>';
$userScript .= YOURUSERSCRIPT;// get user script info
$userScript .= '</script>';
echo $userScript;
}
add_action('wp_head', 'addUserScript');
?>

Codeigniter: css is not working and is eating my code [duplicate]

In my web application using codeigniter. I am trying to use base_url() function but it shows empty results. I have also used autoload helper through autoload file, but then too it doesn't seem to work. Also I had defined base constants but all in vain.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $title; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="<?php echo base_url();?>/css/template/default.css" type="text/css" />
<script type="text/javascript">
//<![CDATA[
base_url = '<?= base_url();?>';
//]]>
</script>
</head>
In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):
$autoload['helper'] = array('url');
Or, manually:
$this->load->helper('url');
Once it's loaded, be sure to keep in mind that base_url() doesn't implicitly print or echo out anything, rather it returns the value to be printed:
echo base_url();
Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:
If this (base_url) is not set then CodeIgniter will guess the protocol, domain and path to your installation.
application/config/config.php, line 13
If you want to use base_url(), so we need to load url helper.
By using autoload $autoload['helper'] = array('url');
Or by manually load in controller or in view $this->load->helper('url');
Then you can user base_url() anywhere in controller or view.
First of all load URL helper. you can load in "config/autoload.php" file and add following code
$autoload['helper'] = array('url');
or in controller add following code
$this->load->helper('url');
then go to config.php in cofig folder and set
$config['base_url'] = 'http://urlbaseurl.com/';
hope this will help
thanks
Check if you have something configured inside the config file /application/config/config.php e.g.
$config['base_url'] = 'http://example.com/';
I think you haven't edited codeigniter files to enable base_url(). you try to assign it in url_helper.php you also can do the same config/autoload.php file. you can add this code in your autoload.php
$autoload['helper'] = array('url');
Than You will be able to ue base_url() like this
<link rel="stylesheet" href="<?php echo base_url();?>/css/template/default.css" type="text/css" />
Apart from making sure you have set config/autoload.php:
$autoload['helper'] = array('url');
Change application/config/config.php from:
$config['base_url'] = 'http://example.com/';
Become a dynamic base url:
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https": "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
And using the host from php to run it on local, below is just an example port.
php -S localhost:2000
If you don't want to use the url helper, you can get the same results by using the following variable:
$this->config->config['base_url']
It will return the base url for you with no extra steps required.
Load url helper in controller
$this->load->helper('url');
Anything if you use directly in the Codeigniter framework directly, like base_url(), uri_string(), or word_limiter(), All of these are coming from some sort of Helper function of framework.
While some of Helpers may be available globally to use just like log_message() which are extremely useful everywhere, rest of the Helpers are optional and use case varies application to application. base_url() is a function defined in url helper of the Framework.
You can learn more about helper in Codeigniter user guide's helper section.
You can use base_url() function once your current class have access to it, for which you needs to load it first.
$this->load->helper('url')
You can use this line anywhere in the application before using the base_url() function.
If you need to use it frequently, I will suggest adding this function in config/autoload.php in the autoload helpers section.
Also, make sure you have well defined base_url value in your config/config.php file.
This will be the first configuration you will see,
$config['base_url'] = 'http://yourdomain.com/';
You can check quickly by
echo base_url();
Reference: https://codeigniter.com/user_guide/helpers/url_helper.html
Question -I wanted to load my css file but it was not working even though i autoload and manual laod why ? i found the solution =>
here is my solution :
application>config>config.php
$config['base_url'] = 'http://localhost/CodeIgniter/'; //paste the link to base url
question explanation:
" >
i had my bootstrap.min.css file inside assets/css folder where assets is root directory which i was created.But it was not working even though when i loaded ?
1. $autoload['helper'] = array('url');
2. $this->load->helper('url'); in my controllar then i go to my
I encountered with this issue spending couple of hours, however solved it in different ways. You can see, I have just created an assets folder outside application folder. Finally I linked my style sheet in the page header section. Folder structure are below images.
Before action this you should include url helper file either in your controller class method/__constructor files or by in autoload.php file. Also change $config['base_url'] = 'http://yoursiteurl'; in the following file application/config/config.php
If you include it in controller class method/__constructor then it look like
public function __construct()
{
$this->load->helper('url');
}
or If you load in autoload file then it would looks like
$autoload['helper'] = array('url');
Finally, add your stylesheet file.
You can link a style sheet by different ways, include it in your inside section
-><link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css" type="text/css" />
-> or
<?php
$main = array(
'href' => 'assets/css/style.css',
'rel' => 'stylesheet',
'type' => 'text/css',
'title' => 'main stylesheet',
'media' => 'all',
'index_page' => true
);
echo link_tag($main); ?>
-> or
finally I get more reliable code cleaner concept. Just create a config file, named styles.php in you application/config/styles.php folder.
Then add some links in styles.php file looks like below
<?php
$config['style'] = array(
'main' => array(
'href' => 'assets/css/style.css',
'rel' => 'stylesheet',
'type' => 'text/css',
'title' => 'main stylesheet',
'media' => 'all',
'index_page' => true
)
);
?>
call/add this config to your controller class method looks like below
$this->config->load('styles');
$data['style'] = $this->config->config['style'];
Pass this data in your header template looks like below.
$this->load->view('templates/header', $data);
And finally add or link your css file looks like below.
<?php echo link_tag($style['main']); ?>
This All Directly Access Function Will Be Loaded Through Helper Class Only.
Like URL, Security, File all Are Helpers and You can Also Load Custom Helpers.
config/autoload.php
$autoload['helper'] = array('url', 'file', 'authorization', 'custom');

WordPress, pass variable from page.php to header.php

I try to create a theme in WordPress, and allow the user for some Page Templates, to load either a Slide-show in the header or to display the title.
Lets say, I have a template name called, Portfolio and another page template called Portfolio with Slide-show In Head.
Can I from within the portfolio.php and portfolio-with-slide.php to send variables in the header.php in order to decide what to display, or have I to create a second header for the second option and load the one need it into the template file with get_header('title') and get_header('slide')
What is the best approach ?
I personally use the second option - create a second header for the second option and load the one need it into the template file with get_header('title') and get_header('slide').
This is the best approach in terms of code maintainability.
A proper solution is to write a filter to replace the title:
function this_is_the_title_now( $title ) {
// can return un-altered $title or can use fancy logic here
return( "This is the new title." );
}
add_filter( 'the_title', 'this_is_the_title_now', 10, 2 );
This can be put into functions.php of your theme, or in page-whatever.php.
since wordpress 5.5 get_header has $args parameter ready to use:
https://developer.wordpress.org/reference/functions/get_header/
You can just put your arguments into get_header like this:
get_header( 'yourheadername', [ 'header_arg' => 'XYZ' ] ); (if you're using customized header.php file, in this case would it be: header-yourheadername.php)
or for default header.php file:
get_header( null, [ 'header_arg' => 'XYZ' ] );
then inside your header file you can use:
<?php echo $args['header_arg']; ?>
inside if or whatever you want :-)
You can use set_query_var to send variables to your header.php file, or any template part file.
For example, in your Portfolio Slideshow template (portfolio-with-slide.php) file:
//portfolio-with-slide.php
set_query_var('includeSlideshow', true);
Then in your header.php file (or a template part file):
//Header.php
$slideshowHeader = get_query_var('includeSlideShow');
//If variable exists and is boolean true
if($slideshowHeader !== null && $slideshowHeader === true) {
//code to include slideshow in header
}

Resources