Global Variable in Functions.php Then Use in Javascript (WordPress) - php

I'm sorry if this is the wrong place. Actually this has been asked before by another user (although it was not the same question) and it was said that this is a PHP question. Unfortunately I am not good enough in PHP to implement the answer.
Here is the [previous question]:https://wordpress.stackexchange.com/questions/82503/cant-get-options-with-datavariable
I am facing the same problem. In my options, I have a slider's option (animation - fade or slide) and then I want to use the value stored in the option and pass it into Javascript in my function.php.
In the option file I have these codes:
// Slider animation options
$of_options_slider_animation = array(
"fade" => __("Fade", "themename"),
"slide" => __("Slide", "themename")
);
and
$of_options[] = array( "name" => __("Slider Animation", "themename"),
"desc" => __("Select the type of animation for the slider.", "themename"),
"id" => "slider_animation",
"std" => "fade",
"type" => "radio",
"options" => $of_options_slider_animation
Later I would pass the option into a js block of code in functions.php like so:
jQuery('.flexslider').flexslider({
controlNav: true,
directionNav: true,
prevText: 'Previous',
nextText: 'Next',
**animation: "<?php echo $smof_data['slider_animation']; ?>",**
animationLoop: false
// animation: "slide"
});
(please notice the bold-ed part)
However, as you may predict, it doesn't work.
I've tried defining the $smof_data like in the previous question (see link above) but still no luck. Here is what I do:
// Fetch options data
global $smof_data;
$smof_data = of_get_options("slider_animation");
Please help, thanks in advance :)
EDIT:
SMOF link: https://github.com/sy4mil/Options-Framework
I am using a blank / starter theme by underscores.me

Solved it :D I use the variable directly within the Javascript scope. Here is the code (just in case)
function mytheme_flexslider() {
if (!is_admin()) {
// Enqueue FlexSlider JavaScript
wp_register_script('jquery_flexslider', get_template_directory_uri(). '/js/jquery.flexslider-min.js', array('jquery') );
wp_enqueue_script('jquery_flexslider');
// Enqueue FlexSlider Stylesheet
wp_register_style( 'flexslider-style', get_template_directory_uri() . '/inc/flexslider/flexslider.css', 'all' );
wp_enqueue_style( 'flexslider-style' );
// FlexSlider custom settings
add_action('wp_footer', 'mytheme_flexslider_settings');
function mytheme_flexslider_settings() {
// Fetch options data
**global $smof_data;?>**
<script>
// Can also be used with $(document).ready()
// flexslider have a fixed height
jQuery(window).load(function() {
// jQuery('.subhead_shadow_bottom').hide();
jQuery('.flexslider').flexslider({
controlNav: true,
directionNav: true,
prevText: 'Previous',
nextText: 'Next',
animation: "<?php echo $smof_data['slider_animation']; ?>",
animationLoop: false
// animation: "slide"
});
});
jQuery(document).ready(function() {
fixFlexsliderHeight();
});
jQuery(window).load(function() {
fixFlexsliderHeight();
}); // BUG: this ends up computing the slide height to the image height, not to the resized height, on page reload
jQuery(window).resize(function() {
fixFlexsliderHeight();
});
function fixFlexsliderHeight() {
// Set fixed height based on the tallest slide
jQuery('.flexslider').each(function(){
var sliderHeight = 0;
jQuery(this).find('.slides > li').each(function(){
slideHeight = jQuery(this).height();
if (sliderHeight < slideHeight) {
sliderHeight = slideHeight;
}
});
// jQuery(this).find('ul.slides').css({'height' : sliderHeight});
// console.log("Fixing slider height to " + sliderHeight);
});
}
// jQuery(document).ready(function($){
// $('.flexslider').flexslider();
// });
</script>
<?php
**// return $smof_data;**
}
}
}
add_action('init', 'mytheme_flexslider');
All are working now. Maybe one little question: Do I need to return $smof_data (the second bold-ed part)? It works both ways.. I need to learn more about varible scopes..

Related

Wordpress 3.8: jQuery not working - no errors

OK,
so I've got this weird situation. I'm trying to include Paul Underwood's simple smooth scroll script (http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery) in a Wordpress one-pager running on Wordpress 3.8.1.
However, the smooth scroll ain't working.
The script works perfectly on JFiddle, I've checked it for errors, but it's a simple copy-paste from the source, so that shouldn't be the problem. I'm pretty sure I've enqueued it properly in functions.php (yes, I also registerd jQuery). And it should work in noConflict.
So what am I missing here? It won't surprise me if it's a stupid little mistake...
Anyway, thanks in advance everyone :)
The HTML:
<img class="arrow" src="<?php bloginfo('stylesheet_directory'); ?>/images/arrow-down.png" alt="scroll down">
The script:
jQuery(document).ready(function($) {
$(document).ready(function() {
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
});
the functions.php
function my_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_style( 'my-style', get_stylesheet_uri() );
wp_register_script( 'my-script', get_template_directory_uri().'/js/my-script.js', array('jquery'), '1.0', true );
wp_enqueue_script( 'my-script' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
As your code says that you have two doc ready handlers and you can remove the inner doc ready first line is better:
jQuery(document).ready(function($) { // keep it, its better.
$(document).ready(function() { //<---remove this line and its closing
so final code should be:
jQuery(document).ready(function($) {
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
}); // end of animate
}); // end of click
}); // end of doc ready
Wordpress uses jQuery instead of $ by default. Try to replace all your $'s to jQuery.
jQuery(document).ready(function() {
jQuery('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = jQuery(target);
jQuery('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
}); // end of animate
}); // end of click
}); // end of doc ready
Try this one.
EDIT: Oh, I've just seen that you are giving the $ as a parameter of the function. My fault.
But have you checked if you probably include jQuery twice?
OK, so I figured it out, guys.
As I predicted, it was some stupid little thing.
There was a relic
body{overflow-x: hidden}
in my stylesheet.
This is what's been trolling me - removed the line, and now everything works fine.
Thanks for the help, though :-)

Using wordpress color picker in post options

I create post options and I want to implement wordpress color picker core inside it
I tried this code I got it from many tutorials and sources but unfortunately It's not working at all, It's like I never added the code.
HTML
<input name="mv_cr_section_color" type="text" id="mv_cr_section_color" value="#ffffff" data-default-color="#ffffff">
PHP
function Colorpicker(){
wp_enqueue_style( 'wp-color-picker');
wp_enqueue_script( 'wp-color-picker');
}
add_action('admin_enqueue_scripts', 'Colorpicker');
JQuery
jQuery(document).ready(function(){
jQuery('#mv_cr_section_color').wpColorPicker();
});
You don't say how you're creating the Theme Options page, but the following is a working example. It's almost the same code as your sample code, but the enqueue is done directly on the custom menu page callback and jQuery is being referenced as $ (note its declaration in ready(function($)):
<?php
/**
* Plugin Name: Testing the Color Picker
*/
add_action( 'admin_menu', 'b5f_demo_menu' );
function b5f_demo_menu()
{
add_menu_page(
'Test',
'Test',
'edit_pages',
'test-slug',
'b5f_callback_function'
);
}
function b5f_callback_function()
{
wp_enqueue_script('wp-color-picker');
wp_enqueue_style( 'wp-color-picker' );
?>
<input name="mv_cr_section_color" type="text" id="mv_cr_section_color" value="#ffffff" data-default-color="#ffffff">
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#mv_cr_section_color').wpColorPicker();
});
</script>
<?php
}
When using admin_enqueue_scripts, the callback function has one parameter $hook_suffix. With it, you can make sure the scripts and styles are only added in the correct screen:
add_action( 'admin_enqueue_scripts', 'b5f_custom_enqueue' );
function b5f_custom_enqueue( $hook_suffix )
{
// CHECK IF CORRECT PAGE, IF NOT DO NOTHING
# if ( 'my_hook-name' != $hook_suffix )
# return;
?>
<script type="text/javascript">
// Use this to check the hook_suffix name
console.log('<?php echo $hook_suffix; ?>');
</script>
<?php
}
Just include a jQuery file and stylesheet file by this script.
// Register Scripts & Styles in Admin panel
function custom_color_picker_scripts() {
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script( 'iris', admin_url( 'js/iris.min.js' ), array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), false, 1 );
wp_enqueue_script( 'cp-active', plugins_url('/js/cp-active.js', __FILE__), array('jquery'), '', true );
}
add_action( 'admin_enqueue_scripts', custom_color_picker_scripts);
Now create a new javascript file as like cp-active.js and keep it avobe defined “/js/cp-active.js” file path using bellows code.
jQuery('.color-picker').iris({
// or in the data-default-color attribute on the input
defaultColor: true,
// a callback to fire whenever the color changes to a valid color
change: function(event, ui){},
// a callback to fire when the input is emptied or an invalid color
clear: function() {},
// hide the color picker controls on load
hide: true,
// show a group of common colors beneath the square
palettes: true
});
Add a textbox to your settings page with a CSS class for the color picker, where you want to display the input text. I have use “color_code” for input $variable.
<input id="color_code" class="color-picker" name="color_code" type="text" value="" />
Please see more details on Add jQuery Color Picker WordPress Theme or Plugin

jqxgrid row selection on mouse click nor working

Im using jqwidjets jqxgrif for one of my project.
In grid i want select a row and edit it in another page(href link).the EDIT link in outside the grid.
currently im using following code to row select.but its only working for keyboard navigation not for mouse select.how do i enable mouse select and pass row index to outside edit link onclick event.
$("#jqxgrid").jqxGrid(
{ width : '100%',
source: dataadapter,
selectionmode: 'singlerow',
altrows: true,
theme: theme,
filterable: true,
autoheight: true,
pageable: true,
columnsresize: true,
//virtualmode: true,
pagesizeoptions: ['10', '15', '20'],
pagesize:20,
sortable: true,
ready: function () {
//$("#jqxgrid").jqxGrid('sortby', 'ObjectId', 'asc');
//$("#jqxgrid").jqxGrid('selectionmode', 'singlerow');
$("#jqxgrid").jqxGrid('selectrow', 0);
},
rendergridrows: function () {
return dataadapter.records;
},
columns: [
I use the following for getting the click and keyboard, hopefully this helps.
$('#jqxgrid').bind('rowselect', function(event) {
var current_index = event.args.rowindex;
var datarow = $('#jqxgrid').jqxGrid('getrowdata', current_index);
// Use datarow for display of data in div outside of grid
});
$("#jqxgrid").bind('rowselect', function (event) {
});

Too much recursion on ajax call

I am usining masonry view to display content with infinite scrolling functionality.
Masonry view part is working fine. For infinite scroll I have tried infinitescroll js
or on the basis of scroll as I have written below code.
Problem :- After first scroll I am facing too much recursion problem.
jQuery(document).ready(function($) {
var $container = jQuery('.main_container');
$container.imagesLoaded(function(){
// options
$container.masonry({
itemSelector: '.pin',
isAnimated: true,
isFitWidth: true,
isAnimatedFromBottom: true
});
});
//for infinite scrollings
jQuery(window).scroll(function() {
if(jQuery(window).scrollTop() + jQuery(window).height() == jQuery(document).height()) {
alert("bottom!");
ajaxurl = "script url here";
var data = {start:startLimit,end:endLimit};
jQuery.get(ajaxurl, data, function(response) {
var $boxes = $(response);
$('.main_container').append( $boxes ).masonry( 'appended', $boxes );
});
}
});
});
I am trying this on wordpress admin section plugin.
After step-by-step checking I found solution , Cause of the problem I am using animate effect in masonry which is conflict some how with wordpress plugin view js.
$container.imagesLoaded(function(){
// options
$container.masonry({
itemSelector: '.pin',
isAnimated: false,
isFitWidth: true,
isAnimatedFromBottom: false
});
});

How can I unbind JQZOOM in my JQuery Script?

I have this script at the moment, which changes an image when a thumbnail has been changed. I then want JQZOOM to be added to that new image. However, if I put it inside the Onclick event, it gets slower and slower the more times you click on it... I guess because its running multiple instances.
Is there anyway to unbind the JQZOOM from something then rebind it to something else?
Here is my jquery at the moment:
var options = {
zoomWidth: 400,
zoomHeight: 325,
xOffset: 25,
yOffset: 0,
position: "right",
lens: true,
zoomType: "reverse",
imageOpacity: 0.5,
showEffect: "fadein",
hideEffect: "fadeout",
fadeinSpeed: "medium",
title: false
};
$('.jqzoom').jqzoom(options);
$('.single-zoom-image').click ( function () {
$('#bigProductImage').attr("src", $(this).attr("zoom"));
$('.jqzoom').attr("href", $(this).attr("extrazoom"));
});
Thanks in advance if anyone can help me.
Cheers!
This can be done as follows:
Modify jqzoom1.0.1.js where the other mouse functions are (around line 90)
//Handle clicked thumbnails changing the zoomed image
$(this).bind('changeimage', function(){
smallimage = new Smallimage( $("img", this) );
largeimage = new Largeimage(a[0].href);
smallimage.loadimage();
});
Call the zoomer as follows:
$(document).ready(function(){
var options = {
zoomWidth: 300,
zoomHeight: 200,
xOffset: 30,
yOffset: 0,
position: 'right',
title: false,
showPreload: false
};
//Handle clicking on the thumbnails, swap the mainimage and recycle the zoomer
$('.seemore').bind('click', function(e) {
e.preventDefault();
$('.jssProductFullImage').attr('src', $(this).attr('href'));
$('.zoomer').attr('href', $(this).attr('href') );
//Recall the zoomer to update the page
$('.zoomer').trigger('changeimage');
});
$('.zoomer').jqzoom(options);
});
$('.jqzoom').removeData('jqzoom');
Did the job for me.

Categories