Run Specific Js on Specific page Wordpress - javascript

I want to run a specific js on a specific page. I.e: wwww.custom.com/english/
I've tried the following two codes (header.php and functions.php) but none of them work.
Code 1:
<script>
if(location.pathname=="/english/")
script.src = /js/custom.js;
</script>
Code 2:
function my_scripts() {
if( is_page( array( 'about-us', 'contact', 'management' ) ){
wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
The header one does not show at all, no error either.
The functions.php is a syntax error.
Any suggestions?
Much Obliged
PS: I'm using WordPress.

You code is great! You are just missing a closing parenthesis:
function my_scripts() {
if( is_page( array( 'about-us', 'contact', 'management' ) ) ){
wp_enqueue_script( 'script-name', 'path/to/example.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
For future reference, in your wp-config.php file you can set debug to true, I believe that this will pick it up.

There is multiple other ways.
Just open your header.php and try to get current page slug or id and put simple if condition it will surely include your js
Code 1
global $post;
$post_slug=$post->post_name;
if($post_slug == 'about'){
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
}
OR Code 2
$currentID= get_the_ID();
//instead of 10 put the your id
if($currentID == 10){
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/example.js"></script>
}

Related

Link Javascript file with wordpress plugin

I am struggling with finishing a basic plugin I created.
I have a plugin folder with the following structure:
Folder_name: Booking
booking.php
js - script.js
css - style.css
js and css are sub folders in the Booking folder.
I have the following function in the booking.php file:
function sc_booking_process() {
return 'html content which uses divs which connect to js and css files';
}
add_shortcode('cinema-booking', 'sc_booking_process');
?>
The booking.php needs to link to the javascript and css files to work properly but no matter what method I do it wont work.
I have tried putting the following before the above function but they still aren't linked to it:
function my_scripts_and_css() {
wp_enqueue_style( 'my-plugin-css', 'css/style.css' );
wp_enqueue_script( 'my-plugin-js', 'js/script.js', array('jquery'), '20200110' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_and_css' );
Any advise would be really appreciated.
function my_scripts_and_css() {
wp_enqueue_style( 'my-plugin-css', plugins_url( '/css/style.css', __FILE__ ) );
wp_enqueue_script( 'my-plugin-js', plugins_url( '/js/script.js',__FILE__ ), array('jquery'), '20200110' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_and_css' );
It should work now! Please try with this
function my_scripts_and_css() {
wp_enqueue_style( 'my-plugin-css', plugin_dir_url( __FILE__ ).'/css/style.css' );
wp_enqueue_script( 'my-plugin-js', plugin_dir_url( __FILE__ ).'/js/script.js', array('jquery'), '20200110' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_and_css' );
You call wrong dir for css and js, please try this one! hope it will work for you

How do I retrieve the current user in wordpress through Javascript?

I have the following code which works. (When I press the button "test" is displayed on the input form.
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/6.1.19/browser.min.js"></script>
<script>
function btn1() {
document.getElementsByName("admin-status")[0].value = "test";
}
</script>
I want to retrieve the username, so I thought I added it correctly, but it says not defined.
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/6.1.19/browser.min.js"></script>
<script>
global $current_user;
$current_user = wp_get_current_user();
function btn1() {
document.getElementsByName("admin-status")[0].value = $current_user;
}
</script>
What am I missing? Thanks. Noob here.
The better way to add localize script
add_action( 'wp_enqueue_scripts', 'wp12311_enqueue_scripts' );
function wp12311_enqueue_scripts() {
wp_enqueue_script( 'wp12311-scripts', 'your_script_path/test.js', array( 'jquery' ), false, true );
wp_localize_script( 'wp12311-scripts', 'test', array(
'current_user' => wp_get_current_user()
) ) );
}
Now in test.js file you can access current user data like
var displayName = test.current_user.display_name;
You'll probably see a " is undefined" in js console and/or other errors. Note that you forgot the php <?php and ?> around the php code, and the $current_user would be "<?php echo $current_user ?>
If you are doing anything more than one line script you really should enqueue script and then localize script to a variable you can use in js on the page anywhere, not mix php and js!

Adding javascript to php (wordpress)? [duplicate]

This question already has answers here:
How to get JavaScript variable value in PHP
(10 answers)
Closed 5 years ago.
So I am helping my friend with his woocommerce WordPress site. He has some short javascript code that needs to be added to the thank you page for the site.
The javascript code takes three variables (totalCost, orderId and setProductId). I can not get to the HTML. So how do I add this code to the PHP and also, how do I access the variables from the PHP and write them into the javascript?
And where in the already existing code should I add it? Is it in the functions.php file for the theme?
I would be super thankful for help!
EDIT:
So would this work?
add_action( 'studentkortet_tracking', 'my_custom_tracking' );
function studentkortet_tracking($order_id){
?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo ($order->order_total - $order->order_shipping); ?>');
sale.setOrderID('<?php echo $order->id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
Here is some working code, answered here
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's the correct way of accessing PHP variables within a script. It utilises the function wp_localize_script() so that PHP variables are accessible in a script file. First include this file in your functions.php file
function example_enqueue_scripts() {
if( is_checkout() ) {
$args = array( 'total_cost' => 443, 'order_id' => 4567, 'set_product_id' => 123 );
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js' );
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
}
add_action( 'wp_enqueue_scripts', 'example_enqueue_scripts' );
Then include this javascript in a file under your theme folder called checkout-script.js for example.
(function( $ ) {
'use strict';
$(function() {
var totalCost = checkout_script.total_cost;
var orderId = checkout_script.order_id;
var setProductId = checkout_script.set_product_id;
exampleFunction( totalCost, orderId, setProductId );
function exampleFunction( totalCost, orderId, setProductId ) {
//Do something in here
//alert(totalCost);
}
});
})( jQuery );
I don't know what setProductId is meant to be as a variable, but the hook you are looking for is woocommerce_thankyou. The $order_id is passed by default, which you can then use to grab the order object. Pretty much all the info related to the order can be accessed through the setter/getter methods on the order object.
/**
* Print Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id ); ?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo $order->get_total() - $order->get_shipping_
(); ?>');
sale.setOrderID('<?php echo $order_id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );
Editing to add an alternative for enqueuing the scripts as suggested by #Andrew-Schultz. Using the woocommerce_thankyou hook gets you easy access to the $order_id, which would otherwise need to be retrieved from the URL. You will still access the javascript variables as he's shown in his answer.
/**
* Enqueue Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id );
$args = array(
'total_cost' => $order->get_total(),
'order_id' => $order_id,
'set_product_id' => 123
);
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js', array(), false, true ); // Last parameter loads script in footer
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );

Execute a short code on a image click?

Not sure to post here or webmasters, I apologize if I got wrong.
Does anyone know of a way to execute a short code on a image click?
I can not find anything on how to do this
Edit: My apologizes
Yes Shortcode means wordpress shortcode
==== Template page ====
<script>
function executeShortCode() {
var url="<?php echo get_template_directory_uri(); ?>/yourAjaxPage.php";
jQuery.post(url,function(data){
console.log(data);
});
}
</script>
==== Ajax page ====
//yourAjaxPage.php
<?php echo do_shortcode('[yourshortcode]'); ?>
Because I just couldn't find answers online to my own question on this, I thought I'd post my solution. Using wp_localize_script to load my shortcodes, here is my example:
// PHP (in functions.php)
<?php
add_action( 'wp_enqueue_scripts', 'custom_add_scripts' );
function custom_add_scripts() {
wp_register_script( 'my_new_js_callname', plugins_url( '/js/filename.js' , __FILE__ ), array(), '1.0.0', true );
wp_enqueue_script( 'my_new_js_callname' );
}
add_action ('template_hook', 'custom_function_name');
function custom_function_name() {
// Because I used if/else statements in my JS, I loaded individual IDs into the array.
$examplea = do_shortcode('[add_to_cart id="118"]');
$exampleb = do_shortcode('[add_to_cart id="119"]');
$examplec = do_shortcode('[add_to_cart id="120"]');
$array = array(
'examplea' => $examplea,
'exampleb' => $exampleb,
'examplec' => $examplec,
);
wp_localize_script( 'my_new_js_callname', 'callword', $array );
Then, on image click or any other JS event you are using do:
// JS (in filename.js)
<script>
document.getElementById('myImg').onclick = function (){
$("#show").html( callword.examplea );
}
</script>
Then the shortcode is executed on my HTML page in there area where I have:
<div id="show"></div>
Get image element by it's id and attach the handler at onclick event something like
html
<img id="myImg" src="" />
JS
<script>
document.getElementById('myImg').onclick = function (){
//execute your short code here.
}
</script>

WP get_post_thumbnail with Backstretch JS

I am using a javascript that's called 'Backstretch' to display an image on the back of my website that resizes when the viewport is getting bigger or smaller. Now I would like to combine it with the get_post_thumbnail function from WordPress so I can set a background image as featured image.
I tried the standard WP function but that doesn't work because it adds tags:
$.backstretch("<?php echo get_the_post_thumbnail( $post_id, $size, $attr ); ?>");
So I need to strip off those tags.. I'm getting close because i'm now getting an url (and image) but it's always the same one even though I set a different featured image on every page
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post_id, $size, $attr ) ); ?>
<script>$.backstretch("<?php echo $url; ?>");</script>
You get the answer to your question in this tutorial: http://sridharkatakam.com/set-featured-image-full-sized-background-posts-pages-wordpress/
Create a backstretch-set.js-file and include
jQuery(document).ready(function($) {
$("body").backstretch([BackStretchImg.src],{duration:3000,fade:750});
});
and then enqueue both js-files (backstretch.js and your backstretch-set.js) in your functions.php
//* Enqueue Backstretch script
add_action( 'wp_enqueue_scripts', 'enqueue_backstretch' );
function enqueue_backstretch() {
//* Load scripts only on single Posts, static Pages and other single pages and only if featured image is present
if ( is_singular() && has_post_thumbnail() )
wp_enqueue_script( 'backstretch', get_bloginfo( 'stylesheet_directory' ) . '/js/jquery.backstretch.min.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_script( 'backstretch-set', get_bloginfo('stylesheet_directory').'/js/backstretch-set.js' , array( 'jquery', 'backstretch' ), '1.0.0' );
wp_localize_script( 'backstretch-set', 'BackStretchImg', array( 'src' => wp_get_attachment_url( get_post_thumbnail_id() ) ) );
Try using the global $post object like so:
<?php global $post; $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'full' ) ); ?>
<script>$.backstretch("<?php echo $url; ?>");</script>

Categories

Resources