I can't figure out how to use jQuery in my WordPress child theme scripts. From my research on SO, I have enqueued my external JavaScript file and have tried coding the jQuery commands in NoConflict mode with no success. Here is the barebones template I'm experimenting on right now (it is essentially a blank page.php and I added a button and paragraph at the bottom):
<?php
/**
*
* Template Name: My JQ Template
*
* #package GeneratePress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
get_header(); ?>
<?php
global $wpdb;
$course_result = $wpdb->get_results('SELECT * FROM SC_COURSES ORDER BY COURSE_NAME');
?>
<div id="primary" <?php //generate_content_class();?>>
</div>
<main id="main" <?php generate_main_class(); // Page title and content ?>>
<?php
do_action( 'generate_before_main_content' );
while ( have_posts() ) : the_post();
get_template_part( 'content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || '0' != get_comments_number() ) : ?>
<div class="comments-area">
<?php comments_template(); ?>
</div>
<?php endif;
endwhile;
do_action( 'generate_after_main_content' );
?>
<br>
<div class="container">
<div>
<input id="testbutton" type="button" onClick="myFunction()" value="POP!">
<p>This is a test</p>
</div>
</div><!-- container -->
</main><!-- #main -->
<?php
do_action( 'generate_after_primary_content_area' );
get_footer();
?>
In functions.php, I have the following:
<?php
function enqueue_child_theme_styles() {
if ( is_page_template( 'jqtemplate.php' ) ) {
//deregister the parent bootstrap style and script
wp_deregister_style( 'bootstrap' );
wp_deregister_script( 'bootstrap' );
wp_deregister_script( 'mycustomjs' );
//enqueue my child theme stylesheet
wp_enqueue_style( 'child-style', get_stylesheet_uri(), array('theme') );
//enqueue bootstrap in the child theme
wp_enqueue_script('bootstrap-js', get_stylesheet_directory_uri().'/bootstrap/js/bootstrap.min.js', array('jquery'), NULL, true);
wp_enqueue_style('bootstrap-css', get_stylesheet_directory_uri().'/bootstrap/css/bootstrap.min.css', false, NULL, 'all');
//Enqueue the custom jQuery specific scripts
wp_enqueue_script('mycustomjs', get_stylesheet_directory_uri().'/js/mycustomjs.js', array('jquery'), NULL, true);
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_child_theme_styles', PHP_INT_MAX);
Within mycustomjs.js, I have the following:
jquery(document).ready(function(){
jquery("p").mouseenter(function(){
jquery("p").text("This is some new text");
});
});
function myFunction() {
var txt;
if (confirm("Press a button, mkay!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("testbutton").value = txt;
}
I am positive the script is loading, because that little demo with changing the button text works. I know the Bootstrap styles and scripts are loading because in the production version they are visible.
I can't make jQuery do anything, though. I have tried adding var j = jQuery.noConflict(); and then using j instead of jquery as described here, I have changed jquery to jQuery, and I have tried putting the jQuery lines directly into the jqtemplate.php header with no success.
I know WordPress includes jQuery, so what am I missing here?
WordPress includes jQuery indeed. But it still has to be loaded.
After loading jQuery you just have to make sure that you use jQuery instead of jquery. like this:
jQuery( document ).ready( function() {
alert( 'test to see if this is working' );
jQuery("p").mouseenter( function() {
jQuery("p").text("This is some new text");
});
});
Related
I have custom post types with JS filtering (based on category). There are simple html boxes + php code with ACF fields what display after select category.
Problem is it take 1 second or more to load all this html boxes so its not so smooth.
This is my JS (file filters.js):
(function($){
$(document).ready(function(){
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url:wp_ajax.ajax_url,
data: { action: 'filter', category: category },
type: 'post',
success: function(result) {
$('.js-filter').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);
This is html of box what is loaded (file content_pozice_box.php)
<a href="<?php echo get_permalink();?>"><div class="vypis_pozice">
<div class="projekt-wrapper">
<?php
$projekt = get_field('projekt');
if( get_field('projekt') == 'XXX' ) {
?>
<div class="logo-wrapper">
<img src="https://YYY.png" class="logo-wrapper-img">
</div><?php
}
if( get_field('projekt') == 'YYY' ) {
?>
<div class="logo-wrapper">
<img src="https://XXX.png" class="logo-wrapper-img">
</div>
<?php
}
?>
<div class="field_projekt"><h3><?php the_field('projekt');?></h3><div class="field_AAA">AAA:
<?php if ( get_field( 'AAA' ) ): ?>
<?php the_field('AAA');?>
<?php else: // field_name returned false ?>
dohodou
<?php endif; // end of if field_name logic ?>
</div></div>
</div>
<?php the_title('<h3>', '</h3>'); ?>
<div class="location-wrapper">
<div class="BBB"><img src="https://BBB.png"><?php the_field('BBB');?></div>
<div class="CCC"><img src="https://CCC.png"><?php the_field('CCC');?></div>
</div>
<div class="DDD"><?php $cat = get_the_category(); echo $cat[0]->cat_name; ?></div><div class="job-button">Otevřít</div>
</div></a>
PHP (loading JS, Ajax, function)
function load_scripts() {
wp_enqueue_script('ajax', get_stylesheet_directory_uri() . '/' . 'template-parts/' .'filters.js', array('jquery'), NULL, true);
wp_localize_script('ajax' , 'wp_ajax',
array('ajax_url' => admin_url('admin-ajax.php'))
);
}
add_action( 'wp_enqueue_scripts', 'load_scripts');
add_action( 'wp_ajax_nopriv_filter', 'filter_ajax' );
add_action( 'wp_ajax_filter', 'filter_ajax' );
function filter_ajax() {
$category = $_POST['category'];
$args = array(
'post_type' => 'pozice',
'posts_per_page' => -1
);
if(isset($category)) {
$args['category__in'] = array($category);
}
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
include("content_pozice_box.php");
endwhile;
endif;
wp_reset_postdata();
die();
}
This won't solve all your problems but the first thing you should do is reduce your database calls. get_field('projekt') is called 4 times, which runs for every iteration of your loop. Oddly, you've already set it to a variable:
$projekt = get_field('projekt');
But you're not using the variable anywhere. So try replacing that first, so that it only runs once per iteration:
if ( $projekt ) {...}
While you're at it you should always escape output for security's sake. I.E. Instead of <h3><?php the_field('projekt');?></h3> replace with <h3><?php echo esc_html( $projekt ); ?></h3>.
To find other sources of inefficiencies you might try the Query Monitor plugin, as well as your browser's dev tools. I'm not sure about your JS. It looks fine to me but perhaps someone else here will notice something.
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>
}
In wordpress, the recommended option to use java script is with wp_enqueue_script(), but what if I want to put some php in that script? for example, look at this code:
$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
<?php if ( !is_front_page() ){ ?>
$('.primary-menu').hide('slow', 'swing');
$('.site-logo').css('height', '60px').css('padding-bottom', '0');
$('#masthead').css('height', '5px');
<?php } ?>
<?php if ( !mida_is_english() ) : ?>
$('.site-header').addClass('shrink');
$("#masthead.site-header.shrink")
.find('.site-logo img')
.attr('src', '<?php echo $upload_dir['baseurl']?>/2015/12/extra-cropped-logo.jpg');
<?php else : ?>
$('.site-header').addClass('shrink');
$("#masthead.site-header.shrink")
.find('.site-logo img')
.attr('src', '<?php echo $upload_dir['baseurl']?>/2015/10/mida-eng-logo.png');
<?php endif; ?>
}
else{ //some more code....
How can I enqueue this code? I can just put it in php file and use wp_enqueue_script() to enqueue that file?
Hope my question make sense..
If you're not willing to add that code to the footer.php file of your site, you can use wp_localize_script() to pass data to your JavaScript
// Localize the script with new data
$data = array(
'is_front_page' => is_front_page(),
'is_english' => mida_is_english()
);
wp_localize_script( 'your-registered-script-handle', 'page_info', $data );
Note that you may need to hook this later than the wp_enqueue_scripts hook, in order for it to work. You can then use it in your JS via:
// This is in a JavaScript file
if ( !page_info.is_front_page ) {
// Do stuff
}
if ( !page_info.is_english ) {
// Do some other stuff
}
All of that said, I recommend just injecting the code you mentioned into wp_footer, instead of messing with localization...
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>
I am having a problem with the responsive menu toggle not expanding on a site I am working on. Essentially when the site is resized below 768px the menu is replaced with a menu toggle that when clicked/tapped it should show the two options About & Shop. However when clicked nothing happens, it simply adds #navigation to the end of the URL.
I have managed to narrow down to one line of code that is for this plugin in my index.php file.
<?php if(sb_slides_display()){sb_slides_display();} ?>
It is a simple WordPress site with WooCommerce using the theme mystile. Link: http://bit.ly/1dvdeb0
If I take out the above code the problem is solved but then of course the slider is no longer activated. Any ideas why or how it can be fixed?
Also, here is the code in context:
<?php
// File Security Check
if ( ! function_exists( 'wp' ) && ! empty( $_SERVER['SCRIPT_FILENAME'] ) && basename( __FILE__ ) == basename( $_SERVER['SCRIPT_FILENAME'] ) ) {
die ( 'You do not have sufficient permissions to access this page!' );
}
?><?php
/**
* Index Template
*
* Here we setup all logic and XHTML that is required for the index template, used as both the homepage
* and as a fallback template, if a more appropriate template file doesn't exist for a specific context.
*
* #package WooFramework
* #subpackage Template
*/
get_header();
global $woo_options;
?>
<?php if(sb_slides_display()){sb_slides_display();} ?>
<?php if ( $woo_options[ 'woo_homepage_banner' ] == "true" ) { ?>
<div class="homepage-banner">
<?php
if ( $woo_options[ 'woo_homepage_banner' ] == "true" ) { $banner = $woo_options['woo_homepage_banner_path']; }
if ( $woo_options[ 'woo_homepage_banner' ] == "true" && is_ssl() ) { $banner = preg_replace("/^http:/", "https:", $woo_options['woo_homepage_banner_path']); }
?>
<img src="<?php echo $banner; ?>" alt="" />
<h1><span><?php echo $woo_options['woo_homepage_banner_headline']; ?></span></h1>
<div class="description"><?php echo wpautop($woo_options['woo_homepage_banner_standfirst']); ?></div>
</div>
<?php } ?>
<div id="content" class="col-full <?php if ( $woo_options[ 'woo_homepage_banner' ] == "true" ) echo 'with-banner'; ?> <?php if ( $woo_options[ 'woo_homepage_sidebar' ] == "false" ) echo 'no-sidebar'; ?>">
Thanks in advance for any help it's greatly appreciated! :)
EDIT: JavaScript page from console error Uncaught TypeError: Object [object Object] has no method 'fitVids' :
/*-----------------------------------------------------------------------------------*/
/* GENERAL SCRIPTS */
/*-----------------------------------------------------------------------------------*/
jQuery(document).ready(function($){
// Fix dropdowns in Android
if ( /Android/i.test( navigator.userAgent ) && jQuery( window ).width() > 769 ) {
$( '.nav li:has(ul)' ).doubleTapToGo();
}
// Table alt row styling
jQuery( '.entry table tr:odd' ).addClass( 'alt-table-row' );
// FitVids - Responsive Videos
jQuery( ".post, .widget, .panel" ).fitVids();
// Add class to parent menu items with JS until WP does this natively
jQuery("ul.sub-menu").parents('li').addClass('parent');
// Responsive Navigation (switch top drop down for select)
jQuery('ul#top-nav').mobileMenu({
switchWidth: 767, //width (in px to switch at)
topOptionText: 'Select a page', //first option text
indentString: ' ' //string for indenting nested items
});
// Show/hide the main navigation
jQuery('.nav-toggle').click(function() {
jQuery('#navigation').slideToggle('fast', function() {
return false;
// Animation complete.
});
});
// Stop the navigation link moving to the anchor (Still need the anchor for semantic markup)
jQuery('.nav-toggle a').click(function(e) {
e.preventDefault();
});
// Add parent class to nav parents
jQuery("ul.sub-menu, ul.children").parents().addClass('parent');
});
From Hobo in the comments above:
fitvids and mobileMenu are both declared in third-party.js. To my eye they look like they don't need noConflict - I think that's for when you want to use $ instead of jQuery, but your code uses jQuery, so should be OK. I now think the problem is that jQuery is being included twice - try removing the second one (v1.8.2, from the Google CDN). It's probably (judging by proximity) where your slicebox.js is included.