Using PHP Options in a Jquery Slider - php

So I'm not sure if I'm missing something obvious on this. (I think it may have something to do with the incompatibility of the two languages, since as far as I'm aware PHP is interpreted on the server?)… I'm pretty new to PHP though.
I'm using the great Jquery Plugin ResponsiveSlides on the front page of my custom WordPress-based site. That works great, with this code:
$(".home-slides").responsiveSlides({
auto: true,
speed: 500,
pause: true,
timeout: 7000,
pager: true,
nav: true,
maxwidth: 1280,
namespace: "home-slides",
prevText: "",
nextText: "",
navContainer:".home-slides",
manualControls: "#home-tabs"
});
However, I want to be able to allow the client to have some control over the plugin, using custom fields on the home page in the wordpress backend. These custom fields can easily be called and correctly display in an alert:
var speed = <?php echo the_field( "speed" ); ?>;
var timeout = <?php echo the_field( "timeout" ); ?>;
However, if I try and insert them as variables or directly with the above PHP, I have no luck. The closest I've got is:
$(".home-slides").responsiveSlides({
auto: true,
speed: <?php echo the_field( "speed" ); ?>,
pause: true,
timeout: <?php echo the_field( "timeout" ); ?>,
pager: true,
nav: true,
maxwidth: 1280,
namespace: "home-slides",
prevText: "",
nextText: "",
navContainer:".home-slides",
manualControls: "#home-tabs"
});
Which displays correctly in the live page source (i.e. timeout: 7000 etc), but breaks the slider. Is there anyway to make this work? Am I missing something?
Thank you all!
EDIT:
Thanks to Tom Kriek's suggestion, I can echo the script correctly. This produces the correct script in the live page source, but the slider still doesn't work. However, if I copy that same script from the page source to the actual file and test this, it works perfectly. It appears for some reason the browser is ignoring the script when PHP echoed.

echo '<script type="text/javascript">
$(".home-slides").responsiveSlides({
auto: true,
speed: '. the_field("speed") .',
pause: true,
timeout: '. the_field("timeout") .',
pager: true,
nav: true,
maxwidth: 1280,
namespace: "home-slides",
prevText: "",
nextText: "",
navContainer:".home-slides",
manualControls: "#home-tabs"
});
</script>';

To incorporate jQuery plugins into WordPress it's a matter of enqueuing the scripts in the correct order (with wp_enqueue_scripts) and to pass our custom meta data to the JavaScript file (with wp_localize_script).
A simple example, note that JS files are inside the plugin sub-folder /my-plugin/js/. The MAIN-PLUGIN-FILE.js corresponds to the jQuery plugin files (slider, player, gallery), add more wp_register_script as needed. And the CUSTOM-CONFIG.js file contains the plugin's initialization.
plugin.php
<?php
/**
* Plugin Name: (SO) Simple jQuery plugin enqueue
* Plugin URI: http://stackoverflow.com/a/25531753/1287812
* Author: brasofilo
*/
class SO_25527828
{
private $plugin_url;
public function __construct()
{
$this->plugin_url = plugins_url( '/', __FILE__ );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
}
public function enqueue()
{
# Enqueue only on specific places
# http://codex.wordpress.org/Conditional_Tags
if( !is_home() && !is_front_page() )
return;
# Can be anything from unheap.com
wp_register_script(
'main_plugin',
$this->plugin_url . 'js/MAIN-PLUGIN-FILE.js'
);
# You'll have to play with dependencies, on_footer and do separately wp_enqueue_script's
# to achieve the exact HTML that the jQ plugin requires
wp_enqueue_script(
'config_plugin',
$this->plugin_url . 'js/CUSTOM-CONFIG.js',
array( 'jquery', 'main_plugin' ), // dependencies
false, // version
true // on footer
);
# Pass PHP values to JS
wp_localize_script(
'config_plugin',
'my_cfg',
array(
'url' => $this->plugin_url, // To load stuff from the plugin's dir
'option' => get_option( 'my_option' ), // Your custom config values, simple value or full object
)
);
}
}
new SO_25527828();
CUSTOM-CONFIG.js, the my_cfg var is printed on header and contains the values that we localized
jQuery(document).ready(function($)
{
console.dir(my_cfg);
});

Related

After passing jQuery Ajax to PHP in Wordpress, how to update global variable prior to use in other function (without using async=false)?

First time posting to StackOverflow. (upvotes appreciated to help me get included in the community)
Despite being new to coding in general, I've been able to work out the following steps in Wordpress thanks to Zac Gordon's very helpful video https://youtu.be/Z0Jw226QKAM?t=216 and demo files https://github.com/zgordon/wordpress-ajax following the steps he outlines:
Pass Nonce and AJAX URL via wp_localize_script
Make AJAX call with Nonce and URL in JavaScript
Hook PHP AJAX Function into Wordpress AJAX Hooks
Use JavaScript to Handle AJAX Response
Although I am able to return the expected result with the AJAX response (which I can print to console) and I am now able to retrieve a value to pass to another function, I am unable to update the value in advance of passing it to other functions.
Based on other StackOverflow conversations (JQuery - Storing ajax response into global variable) I am thinking this is probably an issue with Asynchronous vs Synchronous AJAX calling. However I've further read that setting "async: false" should be avoided at all costs and seems to be deprecated at this point (and didn't help when I tried) so I'm trying to find the proper way to pass this variable from one function to another. Answers I read were not specific to Wordpress which left me at a loss for solving on my own.
The goal is fairly straightforward: get the $(window).height() using AJAX, store as a variable, pass variable into another function in PHP which transforms that variable and adjusts the height of a map Plugin (hook: storymap_heights ).
For starters: I'm currently just trying to get this to work with initial page load, but I would also be curious if it's possible to rerun the functions every time the browser window is resized?
The following code gets me close: I have to refresh twice for the global variable $heights {and/or "get_option( 'jsforwp_heights' )" } to update and properly set the "new" browser window size (so it seems to be storing the variable but not until after it runs through at least once before). The code is currently stored in a Wordpress Snippets plugin, but should work the same as being placed in Functions.php:
<?PHP
global $heights;
if ( null == $heights ) {
add_option( 'jsforwp_heights', 100 );
}
$heights = get_option( 'jsforwp_heights' );
function my_theme_scripts() {
wp_enqueue_script( 'my-great-script', get_template_directory_uri() . '/assets/js/my-great-script.js', array( 'jquery' ), '1.12.4', true );
wp_localize_script(
'my-great-script',
'jsforwp_globals',
[
'ajax_url' => admin_url('admin-ajax.php'),
'total_heights' => get_option('jsforwp_heights'),
'nonce' => wp_create_nonce('nonce_name')
]
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
function screen_height_is(){
check_ajax_referer('nonce_name');
global $heights;
$heights = $_POST['height'];
update_option('jsforwp_heights',$heights);
// set_map_height($heights); //test
$response['success'] = true;
$response['height'] = $heights;
$response = json_encode($response);
echo $response;
wp_die();
}
add_action('wp_ajax_screen_height_is','screen_height_is',1);
add_action( 'wp_ajax_nopriv_screen_height_is', 'screen_height_is',1 );
function set_map_height(){
global $heights;
$testA = get_option('jsforwp_heights');
$testB = "px";
$height = $testA. $testB;
echo $height;
return $height;
}
add_filter('storymaps_heights','set_map_height',10);
//tests for function above
//function set_map_height($heights){
//$testA = '300'; //static option
//$testA = $heights; //works with same loading delay problem
//$testA = $response['height']; //doesn't work even if $response set as global
I have tried nesting the functions without success and calling the set_map_height($heights) from within the screen_height_is() function without success. I also have tried setting #Priority within add_action and add_filter (1 for add_action, 10 for add_filter) to try to get them to wait to run but this also does not seem correct.
The following code is stored in my js file: my-great-script.js:
jQuery(document).ready(function($){
var myResponse;
$.ajax({
type: 'post',
dataType: 'json',
url: jsforwp_globals.ajax_url,
async: false,
data: {
action : 'screen_height_is',
_ajax_nonce : jsforwp_globals.nonce,
width : $(window).width(),
height : $(window).height(),
screen_width : screen.width,
screen_height: screen.height
},
success: function( response ) {
// if( 'success' == response) {
if( response['success'] == true) {
alert("Something went right");
}
else {
alert("Something went wrong");
}
}
})
.done(function(response) {
console.log(response);
})
.fail(function(error) {
alert(error);
})
.always(function() {
console.log("complete");
});
});
Console log prints:
{height: "598", success: true}
complete
I am a little unclear if/how I should be modifying the Success callback to reach my overall goal? Or if the wp_enqueue_script() dependencies need to be modified?
In case this helps, the following filter in PHP hooks into the storymaps-core.php file:
add_filter('storymaps_heights','set_map_height',10);
Where the following wp_enqueue_script resides:
function storymap_external_resources() {
wp_enqueue_style( 'storymap-stylesheet', 'https://cdn.knightlab.com/libs/storymapjs/latest/css/storymap.css' );
wp_enqueue_script( 'storymap-javascript', 'https://cdn.knightlab.com/libs/storymapjs/latest/js/storymap-min.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'storymap_external_resources' );
Any help on what to try next is much appreciated!

Problem with my first basic wordpress plugin

I am trying to create my first worpress plugin!
Actually, the idea is when i click on the button, an ajax request is sent toward php file file (ajax-process.php ), it contains a very basic code to pull some data from database and then displaying it as an alert or other in my home page .
This is my plugin floder (inside wordpress plugins folder)
DB-Puller :
- DB-Puller.php
- ajax-process.php
And js (js_file.js) + css (css_file.css) folders.
Here what contains DB-Puller.php
<?php
/**
* Plugin Name: DB-Puller
* Plugin URI: https://my-web-site.com/
* Description: This is a my firt plugin, it(s allows to display data from database.
* Version: 0.1
* Author: Firest Last name
* Author URI: https://my-web-site.com/
* License: GPL3
*/
function scripts_files_enqueue_scripts() {
// Adding css file
wp_enqueue_style('css_file',plugins_url( 'css/css_file.css', __FILE__ ) );
// Adding JS file
wp_enqueue_script( 'js_file', plugins_url( 'js/js_file.js', __FILE__ ), array('jquery'), '1.0', true );
}
add_action('wp_enqueue_scripts', 'scripts_files_enqueue_scripts');
?>
And This what contains ajax-process.php
N.B : the database table is very basic, it contains just id + text columns
<?php
function my_ajax_action_callback()
{
if (isset($_POST['req']))
{
global $wpdb;
$quer = $wpdb->get_results( "SELECT * FROM wp_custom_table_1" );
$arr = $quer[0]->text;
echo $arr;
die();
}
wp_die(); // required. to end AJAX request.
}
What contains js file
jQuery(function($){
$('body').prepend('<button class="btn" type="button">PULL DATA</button>');
$('button.btn').on('click', function()
{
$.ajax({
url:'http://127.0.0.1/wp522/wp-content/plugins/DB-Puller/ajax-process.php',
method:'POST',
data:{
req:'',
action:'my_ajax_action',
},
success:function(data)
{
alert(data);
},
error:function()
{
alert(erooor);
}
})
})
})
The Alert is sent empty ! Please help me to detect where is the problem!
Thank you.
Looking on the code it does not seem like the Wordpress way of doing this kind of thing.
First you need to include your ajax-process.php in the plugins main file e.g:
require_once plugin_dir_path(__FILE__) . '/ajax-process.php';
Second, you need to register your ajax callback like this:
add_action('wp_ajax_my_ajax_action', 'my_ajax_function');
add_action('wp_ajax_no_priv_my_ajax_action', 'my_ajax_function');
Then register the ajaxUrl in scripts_files_enqueue_scripts() so it accessible from your javascript. The admin-ajax.php file handles all ajax requests:
wp_localize_script(
'js_file',
'ajax',
array(
'ajaxUrl' => admin_url('admin-ajax.php'),
)
);
Then in your javascript you need to use the ajaxUrl and specifying the action which will tell Wordpress which callback should be triggered:
jQuery(function($) {
$('body').prepend('<button class="btn" type="button">PULL DATA</button>');
$('button.btn').on('click', function() {
$.post({
url: ajax.ajaxUrl,
data: {
req: '',
action: 'my_ajax_action',
},
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
});
Here is a good article AJAX in Plugins, explaining how to use ajax in a plugin.

Basic AJAX test in WordPress returning 400 error

So I've followed a very basic tutorial just to figure out the workings of AJAX calls within WordPress. Here are all the relevant bits of code:
In functions.php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() .'/js/my_query.js', array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
In my_query.js
jQuery(document).ready(function($) {
console.log('myquery');
var data = {
'action': 'my_action',
'whatever': ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
and at the bottom of admin-ajax.php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die();
}
This covers all the points in the tutorial, but what I get when I load an admin page is this 400 error, whereas, I should be getting an alert, right?
Any ideas would be truly appreciated, I'm at my wit's end.
Thanks.
You seem to have added your custom code at the end of admin-ajax.php. That is not the correct way to do this. In general, you should never edit a core/admin WordPress file, because it will be overwritten when you update WordPress (among other reasons).
Even ignoring that, the reason why it's not working is that admin-ajax.php is only executed when actually requested, so your callback will be registered too late. You should add your add_action and the relative callback in your theme's functions.php or in a plugin, so that your actions will be registered at due time.

Passing variable from Ajax to PHP in WordPress plugin

I am developing a WordPress plugin and I am trying to pass a variable from ajax to a php file. Both files are inside my plugin folder. The js file is running but when I fire the ajax function, it seems that is not sending a post.
Plugin structure:
-plugin folder
--ajax.js
--folder/example.php
This is my ajax.js
// using jQuery ajax
// send the text with PHP
$.ajax({
type: "POST",
url: "/absoluteurlpluginfolder/folder/example.php",
data: {
'action': 'my_action',
'whatever': 1234
},
// dataType: "text",
success: function(data){
console.log('Connection success.');
// console.log(data);
}
});
And this is my example.php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
alert($whatever);
wp_die(); // this is required to terminate immediately and return a proper response
}
I have two problems:
I cannot see that example.php is receiving anything
How could I use a relative URL to connect with my PHP file? When I try such as 'url: "folder/example.php",' it seems that it starts with "http://localhost/my-wp-project/wp-admin/" and not in my plugin folder, and fails.
I think that the main problem was that I need to add "wp_enqueue_script" and "wp_localize_script". However, I am working in the development of a TinyMCE plugin inside WordPress.
That means that although the JS file is already include, it is not working when I add "wp_enqueue_script" and "wp_localize_script". Why? I do not know but the strange thing is that I made it working with another line.
wp_register_script( 'linked-plugin-script', null);
I have tried with different versions, and the minimum necessary to work is this one above. I can put the URL, version, jquery dependency and false or true. All of them work.
So at the end this is my code and is working.
This is the plugin.php
// Include the JS for TinyMCE
function linked_tinymce_plugin( $plugin_array ) {
$plugin_array['linked'] = plugins_url( '/public/js/tinymce/plugins/linked/plugin.js',__FILE__ );
return $plugin_array;
}
// Add the button key for address via JS
function linked_tinymce_button( $buttons ) {
array_push( $buttons, 'linked_button_key' );
return $buttons;
}
// Enqueue the plugin to manage data via AJAX
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_register_script( 'linked-plugin-script', null);
wp_enqueue_script( 'linked-plugin-script');
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'linked-plugin-script', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'whatever' => '' )
);
}
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = strtoupper($_POST['whatever']);
echo $whatever;
wp_die();
}
And this is the plugin of TinyMCE in JavaScript
// JavaScript file for TinyMCE Linked Plugin
//
//
//
( function() {
tinymce.PluginManager.add( 'linked', function( editor, url ) {
// Add a button that opens a window
editor.addButton( 'linked_button_key', {
// Button name and icon
text: 'Semantic Notation',
icon: false,
// Button fnctionality
onclick: function() {
// get raw text to variable content
var content = tinymce.activeEditor.getContent({format: 'text'});
// using jQuery ajax
// send the text to textrazor API with PHP
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: { 'action': 'my_action',
'whatever': ajax_object.whatever = content
},
beforeSend: function() {
console.log('before send..');
},
success: function(response){
console.log('Success the result is '+response);
}
});
} // onclick function
} ); // TinyMCE button
} ); // tinymce.PluginManager
} )(); // function
Have you seen this page? This is the best tutorial. But you have missed a few things:
You should set global js variable with wp_localize_script() function. Like
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
Replace your url in JS to ajax_object.ajax_url.
IF you wanna work ajax with wp_ajax hooks - you should send all your requests do wp-admin/admin-ajax.php. You can get this url by admin_url('admin-ajax.php');.

How do I correctly include WordPress's user.php in a php script?

I am trying to check if a username is available in wordpress by using ajax with a php script backend, however am unsure of how to do this correctly.
In the checkusername.php script, I include WordPress's user.php like so:
require_once("../wp-includes/user.php");
I call username_exists( $_POST["username"] ) and am greeted with the following error:
Call to undefined function get_user_by() in ...\user.php on line 1613
Note I abbreviated the location. If I include pluggable.php I get a similar error but for
Class 'WP_User' not found in ...\pluggable.php on line 152
Honestly I don't really know how I am supposed to be correctly utilizing the user.php file outside of wordpress pagetemplates so if someone could help me that would be great.
If you are using ajax in WordPress, you don't need to do it "outside" of WordPress. WordPress has it's own filter hook system which allows for ajax callback functions to be run while having FULL access to all of WordPress's functionality.
Have a look at this:
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
Here is a complete example of how to set up an ajax callback properly in WordPress:
PHP Code (place in plugin or functions.php file of theme)
//First enqueue your javascript in WordPress
function your_prefix_enqueue_scripts(){
//Enqueue your Javascript (this assumes your javascript file is located in your plugin in an "includes/js" directory)
wp_enqueue_script( 'your_unique_js_name', plugins_url('js/yourjavascriptfile.js', dirname(__FILE__) ), array( 'jquery' ) );
//OR (simpler but not recommended)
wp_enqueue_script( 'your_unique_js_name', 'http://domain.com/myjavascriptfile.js', array( 'jquery' ) );
//Here we create a javascript object variable called "youruniquejs_vars". We can access any variable in the array using youruniquejs_vars.name_of_sub_variable
wp_localize_script( 'your_unique_js_name', 'youruniquejs_vars',
array(
//To use this variable in javascript use "youruniquejs_vars.ajaxurl"
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'your_prefix_enqueue_scripts' );
//This is your Ajax callback function
function your_ajax_callback_function_name(){
//Get the post data
$username = $_POST["username"];
//Run any WordPress function you want in this ajax callback
if ( username_exists( $username ) ){
$array_we_send_back = array( 'message' => __( 'This user exists', 'textdomain' ) );
}
else{
$array_we_send_back = array( 'message' => __( 'This user does not exist', 'textdomain' ) );
}
//Make sure to json encode the output because that's what it is expecting
echo json_encode( $array_we_send_back );
//Make sure you die when finished doing ajax output.
die();
}
add_action( 'wp_ajax_' . 'your_ajax_callback_function_name', 'your_ajax_callback_function_name' );
add_action( 'wp_ajax_nopriv_' . 'your_ajax_callback_function_name', 'your_ajax_callback_function_name' );
And then this goes in your javascript file:
jQuery(document).ready(function($){
/**
* When your ajax trigger is clicked
*
*/
$( document ).on( 'click', '.my-button', function(event){
event.preventDefault();
// Use ajax to do something...
var postData = {
action: 'your_ajax_callback_function_name',
username: 'test_username_1',
}
//Ajax load more posts
$.ajax({
type: "POST",
data: postData,
dataType:"json",
url: youruniquejs_vars.ajaxurl,
//This fires when the ajax 'comes back' and it is valid json
success: function (response) {
alert( response.message );
}
//This fires when the ajax 'comes back' and it isn't valid json
}).fail(function (data) {
console.log(data);
});
});
});
do not include files manually, use standard wordpress Ajax API
https://codex.wordpress.org/AJAX_in_Plugins
If you need access to WordPress function you will have to include wp-load.php
require_once("wp-contents/wp-load.php");
But this is not best practice, you shouldn't load the file directly.
Instead you can follow instructions on how to use WordPress ajax API as in the answer of kkarpieszuk
(https://codex.wordpress.org/AJAX_in_Plugins)
These answers are fine if you are writing a plugin that is to be distributed out into the world, and you really need it to play nice with the rest of the WordPress landscape, and you don't care about performance. If you have a lot of plugins in your site... especially large ones like BuddyPress, then running ajax calls through the standard WP ajax pipeline can be very inefficient due to the fact that all of the plugins get loaded and processed, and the init routine gets called on all of the plugins for every ajax call. Coming from a non-WordPress world, this seems crazy to me. 99% of ajax calls don't need all of that infrastructure to be set up to do what they need to do.
To avoid this, set up your ajax php page to use the SHORTINIT code, and load the required files in the header. ( See also here: https://wordpress.stackexchange.com/questions/173002/how-declare-ajax-functions-ussing-shortinit )
For access to wpdb, get_current_user, and check_ajax_referer, I used the following the top of my ajax page:
N.B. our install has wordpress in the /wp folder, NOT the root folder! Your path names may be different
the file below might be something like /plugins/myplugin/my_ajax_event_handler.php
...and it would be called directly from $.ajax in the client javascript
<?php
define('SHORTINIT', true);
//IMPORTANT: Change with the correct path to wp-load.php in your installation
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp/wp-load.php';
include_once $path . '/wp/wp-includes/wp-db.php';
include_once $path . '/wp/wp-includes/formatting.php';
include_once $path . '/wp/wp-includes/capabilities.php';
include_once $path . '/wp/wp-includes/session.php';
include_once $path . '/wp/wp-includes/user.php';
include_once $path . '/wp/wp-includes/meta.php';
include_once $path . '/wp/wp-includes/pluggable.php';
wp_cookie_constants( );
wp_plugin_directory_constants();
my_ajax_event_handler();
function my_ajax_event_handler() {
global $wpdb;
// A nonce should be passed in from the client in the post field "security"
check_ajax_referer( 'my_ajax_event_handler', 'security' );
... do all my cool ajax stuff ...
die();
}
?>
Note that I'm working in a large corporate environment, and expect to be forced to do work to upgrade my code whenever we upgrade WordPress. This method works for me, but the normal wp_ajax_ way is definitely safer.

Categories