Using Wordpress Customizer in Javascript - javascript

I have made a customized control for the Wordpress Customizer and I would like to set my control inside a script (Instafeed.js), to change the limit number.
Following this answer this is how I did it so far
<script type="text/javascript">
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: var imglimit = <?php echo json_encode($imglimit); ?>;,
});
userFeed.run();
</script>
Functions
$wp_customize->add_setting(
'imglimit',
array(
'default' => '',
'section' => 'section',
));
$wp_customize->add_control('imglimit', array(
'label' => __('test'),
'section' => 'section',
'settings' => 'imglimit',
'type' => 'select',
'choices' => array(
'5' => '5',
'10' => '10',
'20' => '20',
),
));
function theme_customizer()
{
$imglimit = get_theme_mod('imglimit');
}
Could anyone tell me where is the mistake ? I've been searching for this for a while.

Well, you've got a syntax error here :)
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: var imglimit = <?php echo json_encode($imglimit); ?>;,
// ^^^^^^^^^^^^ here and here ^
});
So, you should change that block of code to
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: <?php echo json_encode($imglimit); ?>,
});
Actually you don't necessarily need to json encode here since it's just a number. But if that was some array or object, yes, you should've encoded that.
And in your php code you should make $imglimit global:
function theme_customizer()
{
global $imglimit;
$imglimit = get_theme_mod('imglimit');
}
Or just put that into js:
var userFeed = new Instafeed({
get: '',
tagName: '',
clientId: '',
limit: <?php echo json_encode(get_theme_mod('imglimit')); ?>,
});

Related

Converting date types for datepicker entry

I'm working on a calendar for wordpress, so I have the following issue: the data i get from the query does not match the datepicker format
The parts to acquire the arrays are following
<?php
$my_array = array();
// the query
$args=array(
'post_type' => 'eventos',
'order'=>'ASC');
$posts = get_posts( $args );
if ( $posts ) {
foreach ( $posts as $post ) {
$my_array[] = array(
'Title' => $post->post_title,
'Date' => date_format(date_create('#'. strtotime(get_field('data-event'))), 'r') . "\n"
,
);
}
}
print_r($my_array);
?>
var events = [
{ Title: "Evento 1", Date: new Date("05/20/2020")},
{ Title: "Evento 2", Date: new Date("05/20/2020")},
{ Title: "Evento 3", Date: new Date("05/21/2020")},];
ConsoleLog Image
any ideas how can I make them equal?

How to add a javascript api to wordpress function.php

I'm trying to add an sms api to Wordpress which sends an order confirmation message using Woocommerce hooks. After some research, I found the following code here which works the same way.
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
//Now will fetch customer/buyer id here
$customer_id = $order->user_id;
//now finally we fetch phone number
$billing_phone = get_user_meta( $customer_id, 'billing_phone', true );
// Now put your HTTP SMS API URL . I PUT WHICH WE ARE USING
$jsonurl = "http://tsms.thirdeyegoa.com/api/sendmsg.php?user=USERNAME&pass=PASSWORD&sender=MYSENDERID&phone=".$billing_phone."&priority=ndnd&stype=normal&text=MY MESSAGE TO CUSTOMER.";
// NOW WILL CALL FUNCTION CURL
$json = curl($jsonurl);
return $order_id;
}
The Api Code my sms gateway provided is
// Include provided Java Script
<script language="javascript" src="https://domainapi.js" type="text/javascript"> </script>
<script language="javascript">
// Replace your API key at below line
var apikey = 'ABCDEFGH1234567890abcdefghQWERTY123=';
// Form your data object
var mail_details = { email : 'John.Doe#foo.com', msgid : '82', listname : '', prefix : '', firstname : 'John', middlename : '', lastname : 'Doe', telephone : '', address : '', city : '', state : '', pincode : '', country : '', mobile : '9999999999', designation : '', company : '', companyphone : '', birthdate : '', anniversary : '', extra1 : '', extra2 : '' }
call_api(apikey, 'sendSingleSMS', mail_details, function(response) { document.getElementById('show').innerHTML=response; });</script>
Please tell me how to integrate this API in the above script for Wordpress.
Presumably, you are trying to blend your API's script into the "WordPress way" and load some data from WooCommerce's order. First, you'd want to register your scripts in your main plugin file:
add_action( 'wp_enqueue_scripts', 'so_38554614_enqueue_scripts' );
function so_38554614_enqueue_scripts(){
wp_register_script( 'your-api', 'https://domainapi.js', array(), '1.0', true );
wp_register_script( 'your-script', 'path-to-your-script.js', array('your-api'), '1.0', true );
}
And then you'll want to load them on the payment complete page. You will also want to take advantage of wp_localize_script() to pass some variables to the script.
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
wp_enqueue_script('your-api');
wp_enqueue_script('your-script');
$l18n = array( 'mail_details'=>
array(
email' => $order->billing_email,
'msgid' => 82,
'listname' => '',
'firstname' => $order->billing_first_name,
'middlename' => '',
'lastname' => $order->billing_last_name,
'telephone' => $order->billing_phone,
'address'= >$order->billing_address_1 . ' ' . $order->billing_address_2,
'city' => $order->billing_city,
'state' => $order->billing_state,
'pincode' => '',
'country' => $order->billing_country,
'mobile' => $order->billing_phone
'designation' => '',
'company' => $order->billing_company,
'companyphone' => '',
'birthdate' => '',
'anniversary' => '',
'extra1' => '',
'extra2' => ''
),
'apikey' => 'ABCDEFGH1234567890abcdefghQWERTY123=' );
wp_localize_script( 'your-script', 'Your_JS_Object', $l18n );
wp_localize_script()
return $order_id;
}
And finally, your javascript file, stored somewhere in your plugin. It takes advantage of the javascript object Your_JS_Object which was created by wp_localize_script():
// Java Script path-to-your-script.js
call_api( Your_JS_Object.apikey, 'sendSingleSMS', Your_JS_Object.mail_details, function(response) { document.getElementById('show').innerHTML=response; });

Stripe AJAX PHP and JavaScript

The below is my code I'm using for my Stripe Subscription Payments, because the site I'm implementing this into is AngularJS I want to keep the site from Refreshing so I'm opting for this AJAX option.
I have commented out a piece of the PHP which is
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));
If I exclude this, the payment goes through once and I'm unsure how this application is able to process the charge if there is no call for it in the PHP file.
If I include the above snippet then the charge goes through twice.
My config.php only has require_once('Stripe.php'); along with my API keys.
So I'm hoping someone could explain why the charge goes through without the charge code piece in there if my code is actually okay for me to continue with.
HTML
<button id="proBtn">Subscribe</button>
JavaScript
Stripe.setPublishableKey('HIDDEN');
$('#proBtn').click(function(){
var token = function(res){
var $input = $('<input type="hidden" name="stripeToken" />').val(res.id);
var tokenId = $input.val();
var email = res.email;
setTimeout(function(){
$.ajax({
url:'/assets/lib/charge.php',
cache: false,
data:{ stripeEmail : email, stripeToken:tokenId, stripePlan: 'pro' },
type:'POST'
})
.done(function(data){
// If Payment Success
console.log(data);
$('#proBtn').html('Thank You').addClass('disabled');
})
.error(function(){
$('#proBtn').html('Error, Unable to Process Payment').addClass('disabled');
});
},500);
//$('form:first-child').append($input).submit();
};
StripeCheckout.open({
key: 'HIDDEN', // Your Key
address: false,
amount: 500,
currency: 'gbp',
name: 'Pro Account',
description: '',
panelLabel: 'Checkout',
allowRememberMe: false,
token: token
});
return false;
});
charge.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/assets/lib/config.php');
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$plan = $_POST['stripePlan'];
if ( $plan == 'pro' ) {
$amount = 500;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'pro';
}
if ( $plan == 'team' ) {
$amount = 2000;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'team';
}
Stripe_Plan::retrieve("pro");
Stripe_Plan::retrieve("team");
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => $plan
));
try {
/*
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));*/
echo 'success';
} catch(Stripe_CardError $e) {
echo "The card has been declined";
echo $token;
}
print_r($token);
echo '<br/>';
print_r($email);
echo '<br/>';
echo $customer->id;
echo '<h1>Successfully charged '.$amountFormat.'!</h1>';
?>
When you create a customer in Stripe it automatically charges them if you pass in a plan. You're basically saying create this customer and sign them up for this plan. That's why you are charging them twice.
Here's a link to the Customer API:
https://stripe.com/docs/api#create_customer

Load wordpress posts into Javascript array of objects

I'm trying to call a list of my Wordpress posts and save them to a Javascript array of objects (JSON, really). I want something like:
var articles = [
{
title: 'Title 1',
author: 'Author 1',
byline: 'Byline 1'
},{
title: 'Title 2',
author: 'Author 2',
byline: 'Byline 2'
}
]
I'm new to PHP so don't quite understand how looping in and out of the <?php ?> tags works, nor how variables and functions work in this sense. I'm trying the following:
<script>
var articles = [];
<?php
$args = array( 'numberposts' => -1);
$posts= get_posts( $args );
if ($posts) {
foreach ( $posts as $post ) { ?> // exit PHP
var obj = {}; // Create a JS object
obj.title = <?php the_title(); ?>; // Append the title to the object
obj.byline = <?php the_excerpt(); ?>; // Append the byline
articles.push(obj); // Push object into the array
<?php }
}
?>
</script>

Count and list all posts user has posted in all categories

I have just discovered this awesome wordpress function
<?php echo 'Number of posts published by user: ' . count_user_posts( ); ?>
Im busy making a graph which displays on a pie chart how many posts the user has done per category. (chars.js)
Is there any way to make a loop almost where i could get the values for each category the user has posted in.
Id like to future proof it so if more categories are added i dont have to go and write something like this
<?php echo 'Number of posts published by user: ' . count_user_posts( 5 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 7 ); ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( 8 ); ?>
Is there a way where i can just get a category breakdown of how many posts a user has posted in all categories
Thanks for any help
Try this code:
Just set which type of user's do you want at array:
<?php $args = array(
'blog_id' => $GLOBALS['blog_id'],
'role' => 'subscriber',//"Super Admin" or "Administrator" or "Editor" or "Author" or "Contributor"
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
'meta_query' => array(),
'include' => array(),
'exclude' => array(),
'orderby' => 'login',
'order' => 'ASC',
'offset' => '',
'search' => '',
'number' => '',
'count_total' => false,
'fields' => 'all',
'who' => ''
);
php get_users( $args );
foreach ($blogusers as $user) { ?>
<li>
<?php $user_id = $user->ID ?>
<?php echo 'Number of posts published by user: ' . count_user_posts( $user_id ); ?>
</li>
<?php } ?>
Thanks.
I think you are misunderstanding the count_user_posts function. It's argument is for user id and not for category id.
Anyways, once you have the desired user id (if i understood well, you want to display the post count for every category where the user was the post author) you can do something like this:
$user_id = 124;
/* Get all categories */
$categories = get_terms("category");
/* Loop for each category to count the posts of the user */
foreach($categories as $category)
{
$cat_name = $category->name;
$cat_id = $category->term_id;
$post_count = count(get_posts("cat=$cat_id&post_author=$user_id"));
echo "The user $user_id has $post_count posts in the $cat_name category";
}
Here is the completed code, thanks for the help everyone
<script type="text/javascript">
var pieData = [
<?php
$user_id = get_query_var('author');
$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
//get all posts from author
$args = array(
'post_type' => 'post',
'author'=> $queried_object->ID
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
//put categories in array
$cat = get_the_category( get_the_ID() );
$terms[] = $cat[0]->term_id;
endwhile;
wp_reset_query();
endif;
//count matching categories (array vals)
$countVal = array_count_values($terms);
foreach($countVal as $count){
$color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
echo " {
value: ".$count.",
color:'".$color."'
},";
}
?>
]
var myPie = new Chart(document.getElementById("piec").getContext("2d")).Pie(pieData);
</script>

Categories

Resources