How to debug PHP script not executing? - javascript

I'm working on a wordpress page here http://beta.fray.it/invite and on clicking the Twitter icon I have this onclick attribute set on a list element
onclick="window.location.href = '<?php echo get_template_directory_uri(); ?>/components/invite/twitter/redirect.php';">
this takes me to the php file which should redirect users to Twitter for authentication. I got this working on another server I use for testing, but not here. What happens is that I see content from the main page http://beta.fray.it but no redirection. What is the reason for this?

After you enable WP_DEBUG and WP_DEBUG_LOG in wp-config.php (WP_DEBUG is disabled by default since WP_DEBUG is set to false).
debug.log is generated in your /wp-content/ directory upon an error, warning, a notice or a log call.
You can also utilize a wrapper function to centralize your log calls
if(!function_exists('_log')){
function _log( $message ) {
if( WP_DEBUG === true ){
if( is_array( $message ) || is_object( $message ) ){
error_log( print_r( $message, true ) );
} else {
error_log( $message );
}
}
}
}
you can read more about that here
Check out the codex as well:
http://codex.wordpress.org/Debugging_in_WordPress

try changing your link href
onclick='window.location.href =' + "<?php echo get_template_directory_uri(); ?>" + '/components/invite/twitter/redirect.php';

Related

Improving upon a feature on a Wordpress site that changes phone number displayed to user in the header based on their IP address

My question is regarding suggestions for improvements of a feature I created on a Wordpress site that changes the phone number displayed to user in the header based on their IP address. The default is a 1-866 number to be displayed if area does not appear to be serviced etc.
In my functions.php file I created the below functions to use ipinfo.io to find the city of the user, compare it to the field of city I created to be associated with each location post and then if there is a match the second function returns the phone number field associated with that location. See functions below:
//Returns users city based on IP address
function get_the_user_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//Checks if IP is from shared internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//Checks if IP is passed from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
//Most trustworthy source of IP address
$ip = $_SERVER['REMOTE_ADDR'];
}
//$ip='104.238.96.194'; //--used this to test different IP addresses--
//Uses ipinfo.io to find location information based on IP address
$details = json_decode(file_get_contents("https://ipinfo.io/{$ip}"));
//Returns city value from the details array
$city=$details->city;
return apply_filters('wpb_get_ip', $city );
}
//Returns correct phone number based on a user's location
function zip_display(){
$args = array(
'posts_per_page' => -1,
'post_type' => 'Locations',
'post_status' => ('publish')
);
$wp_query = new WP_Query($args);
//var_dump($wp_query);
if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
$userCity=get_the_user_ip();
$stateField=get_field('state');
$cityField=get_field('city');
$phoneField=get_field('phone_number');
if($userCity==$cityField){
return ( '<span class="phone-span">' . $phoneField . '</span>');
}
endwhile;
wp_reset_postdata();
endif;
}
To display the correct phone number in the header I inserted a <div> element with the id of phone directly into an auxiliary header like so:
Then to target this div id I inserted the below JavaScript directly into my footer.php
<script>document.getElementById("phone").innerHTML = '<?php echo zip_display(); ?>';</script>
Is this an acceptable way to go about doing this? Everything is working correctly more or less right now. The only issue I am having so far is it seems for at least one person neither the default 1-866 number is being displayed to them nor a specific number based on their location? Does anyone have any ideas why that would be? Does it possibly have to do with a browser setting that does not allow JavaScript scripts to be shown in the way I constructed it?
The zip_display() function in your posted code will only return a span element if the $userCity matches the $cityField. You need to return the span containing the default phone number if the cities do not match. Change your condition to something like this:
if($userCity==$cityField){
return ( '<span class="phone-span">' . $phoneField . '</span>');
}else{
return ( '<span class="phone-span">' . $defaultPhoneNumber . '</span>');
}
In order to improve the functionality of this feature I did the following:
In my get_the_user_ip function I decided to use the free WordPress plugin GeoIP Detection, instead of ipinfo.io
See modification to get_the_user_ip function below:
`//Returns users city based on IP address`
function get_the_user_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//Checks if IP is from shared internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//Checks if IP is passed from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
//Most trustworthy source of IP address
$ip = $_SERVER['REMOTE_ADDR'];
}
$record = geoip_detect2_get_info_from_ip($ip, NULL);
$city=$record->city->name;
return apply_filters('wpb_get_ip', $city );
}
In my zip_display function I added a return statement outside of while loop. In order to return a default phone number if the user's city cannot be matched to a location. This works better than an if/else statement because it will only execute once the loop has completed all iterations.
function zip_display(){
$args = array(
'posts_per_page' => -1,
'post_type' => 'Locations',
'post_status' => ('publish')
);
$wp_query = new WP_Query($args);
if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
$userCity=get_the_user_ip();
$cityField=get_field('city');
$phoneField=get_field('phone_number');
if($userCity==$cityField){
return ('<a class="phone-span" href="tel:1-'. $phoneField . '">' . $phoneField . '</a>');
}
endwhile;
return('<a class="phone-span" href="tel:1-866-000-0000">1-866-000-0000</a>');
wp_reset_postdata();
endif;
}
Lastly I modified my footer.php file, separating my JavaScript script into a variable so that the script would not throw an Uncaught TypeErron: Cannot read property '....' of null.
<script>
var ipphone = '<?php echo zip_display(); ?>'
if(ipphone){document.getElementById("phone").innerHTML = ipphone;}
</script>

Embed clickwork7 tracking code with the transaction ID in Woocommerce

In Woocommerce, I was looking to get order ID just before payment, when the order is created. I found this answer below:
Get the order ID in checkout page before payment process
What I need is to pass in tracking script the transaction ID (as specified on the script) and I should be able to track in clickwork7 dashboard:
<script type="text/javascript" src="https://clickwork7secure.com/p.ashx?
o=45875&e=12995&f=js&t=TRANSACTION_ID"></script>
But the transaction ID seems to be empty after a purchase in Paypal for example, so may be I should pass the order ID instead.
The Order received page seems to be the right place, but for cancelled or failed orders, Where and how to embed this script?
Any help is appreciated.
Updated: It is possible to use many different hooks for that:
wp_head
wp_footer
woocommerce_thankyou
You can try to use the:
Order id (Is easy to get it)
Order Key: $order_key = get_post_meta( $order_id, '_order_key', true );
Transaction id: $transaction_id = get_post_meta( $order_id, '_transaction_id', true );
1) Using woocommerce_thankyou hook: The simpler way as the Order Id is a hook argument:
add_action( 'woocommerce_thankyou', 'checkout_clickwork_js_script', 22, 1 );
function checkout_clickwork_js_script( $order_id ) {
if ( ! $order_id ) return; // Exit
$transaction_id = get_post_meta( $order_id, '_transaction_id', true );
$order_key = get_post_meta( $order_id, '_order_key', true );
if( ! empty($transaction_id) ){
$value = $transaction_id; // TRANSACTION ID
}
elseif( ! empty($order_key) ){
$value = $transaction_id; // ORDER KEY
}
else {
$value = $transaction_id; // ORDER ID
$url = "https://clickwork7secure.com/p.ashx?o=45875&e=12995&f=js&t=$value";
?><script type="text/javascript" src="<?php echo $url; ?>"></script> <?php
}
Code goes in function.php file of your active child theme (or active theme). It should work.
2) Using wp_head hook:
add_action( 'wp_head', 'checkout_clickwork_js_script', 998 );
function checkout_clickwork_js_script() {
// Only order-received page
if( is_wc_endpoint_url('order-received') ) :
global $wp;
$order_id = absint( $wp->query_vars['order-received'] );
if ( ! $order_id || empty($order_id) )
return; // Exit
$transaction_id = get_post_meta( $order_id, '_transaction_id', true );
$order_key = get_post_meta( $order_id, '_order_key', true );
if( ! empty($transaction_id) ){
$value = $transaction_id; // TRANSACTION ID
}
elseif( ! empty($order_key) ){
$value = $transaction_id; // ORDER KEY
}
else {
$value = $transaction_id; // ORDER ID
$url = "https://clickwork7secure.com/p.ashx?o=45875&e=12995&f=js&t=$value";
?><script type="text/javascript" src="<?php echo $url; ?>"></script> <?php
endif;
}
Code goes in function.php file of your active child theme (or active theme). It should work.
The condition if( is_wc_endpoint_url('order-received') ) : can be extended to handle cancelled and failed orders custom endpoints too …
Similar answers:
Add Order data in Adword Conversion Code in Woocommerce
Linkwise Affiliate integration in Woocommerce thankyou page

Wordpress and CSV file. Can it work ?

I have a small problem. On my wordpress based website I want to create an Order-Status form where people can use a code and check their order's progress. It's not an online store so I don't use woocommerce. The file containing the order's progress is a CSV file.
I tried to use that through a function but didn't work. I even tried Javascript but my code can't find the file on server :(
My question is: What language and what technique should I use for my need.
Thank a lot guyz.
I think this is what you are looking for without the need of any libraries:
First You create a form (the form action can be your homepage since we will be listening for the $_GET parameters on init, which is run on every page load):
<form action="<?php echo site_url() ?>">
<input type="hidden" name="csv_export" value="order_status" />
<input type="text" name="code" />
<input type="submit" value="Download Report" name="download_report" />
</form>
Than you need to add an action on init in functions.php to listen for the get parameter csv_export in order to start your functionality to prepare the csv file and output it for download: (we are using the exit(); function after we create csv to make sure that nothing else runs after this process.)
function check_for_export() {
if ( isset( $_GET['csv_export'], $_GET['code'] ) && $_GET['csv_export'] == 'order_status' ) {
ob_end_clean();
export_order_status_csv( $_GET['code'] );
exit();
}
}
}
add_action('init', 'check_for_export');
Now you can start the functionality to generate the csv report. This function depends on how you are fetching the data but you can follow this example to set the headers and output the report:
function export_order_status_csv( $code ) {
// Make a DateTime object and get a time stamp for the filename
$date = new DateTime();
$ts = $date->format( "Y-m-d-G-i-s" );
// A name with a time stamp, to avoid duplicate filenames
$filename = "order-statuses-export-$ts.csv";
// Tells the browser to expect a CSV file and bring up the
// save dialog in the browser
header( 'Pragma: public' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Content-Description: File Transfer' );
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=' . $filename );
header( 'Content-Transfer-Encoding: binary' );
// This opens up the output buffer as a "file"
$fp = fopen( 'php://output', 'w' );
//This needs to be customised from your end, I am doing a WP_Query for this example
$results = new WP_Query();
if ( $results->have_posts() ) {
//This is set to avoid issues with special characters
$bom = ( chr( 0xEF ) . chr( 0xBB ) . chr( 0xBF ) );
//add BOM to fix UTF-8 in Excel
fputs( $fp, $bom );
// Set the headers of the csv
fputcsv( $fp, [
'orderID',
'orderDate',
'orderTotal'
] );
while ( $results->have_posts() ) {
$results->the_post();
//Here we are inserting the row data per result fetched
fputcsv(
$fp,
[
get_the_ID(),
get_the_date(),
'your_custom_data'
]
);
}
wp_reset_query();
// Close the output buffer (Like you would a file)
fclose( $fp );
} else {
fputcsv( $fp, [ 'No Results' ] );
fclose( $fp );
}
}
When exporting a csv you have to hook to an action which is processed before anything has been outputted. There cannot be any output before creating the csv file since we are updating the headers.
If you want to read the data from a csv file and manipulate it to customise your csv export you can use this function instead of the WP_Query in example above: http://php.net/manual/en/function.fgetcsv.php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
I actually used PHPExcel in a previous project that achieved what you're after, though I see it's been deprecated in favour of PhpSpreadsheet library. So I would use that one!
What both libraries can essentially do (amongst many other things) is parse the spreadsheet and return the relevant information based on what you request.
So you could put your spreadsheet in a separate directory which you then use the PhpSpreadsheet library to extract information from - and present to the customer in whatever way you see fit.

Wordpress ajax theme. Ajax does not work. No new data in table in db

I cant understand why my code does not work.
I have a tabel wp_subscibe with id, user_id and post_id. I want after click on button to add this data to my db by ajax. Please, look at my code.
This is my html in single.php:
<button type="submit" name="subscribe" id="subscribe">Subscribe</button>
<input id="postId" type="hidden" value="<?php the_ID(); ?>" />
My subscribe.js:
onSubscribe: function() {
var $onSubscr = $('#subscribe');
$onSubscr.on('click', function() {
var $el = $(this),
post_id = $('#postId').val(),
$.ajax({
type:"POST",
url: admin_url.ajaxurl,
dataType:"json",
//data : 'action=subscribeOn&post_id='+post_id
data: {
action: 'subscribeOn',
post_id: post_id
},
cache: false
});
return false;
});
}
And functions.php:
wp_register_script( 'subscribe', THEME_DIR . '/js/subscribe.js', array(), '', false );
wp_enqueue_script( 'subscribe' );
wp_localize_script( 'subscribe', 'admin_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
function subscribeOn() {
global $wpdb, $user_id, $post_id;
$user_id = get_current_user_id();
$post_id = $_POST['post_id'];
// $table_name = $wpdb->prefix . "subscribe";
$wpdb->insert("wp_subscribe", array( 'user_id'=>$user_id, 'post_id'=>$post_id), array('%s','%s'));
}
add_action( 'wp_ajax_nopriv_subscribeOn', 'subscribeOn' );
add_action('wp_ajax_subscribeOn', 'subscribeOn)');
Can anybody tell me where is my problem? Nothing happens in wp_subscribe in db. I try so many ways, but nothing works.
For debug of javascript you need to get used to using the console (for chrome, right click on the page and "inspect element" you will see console on the top of the pop up. This will list any errors or outputs from js.
A common mistake with jQuery and wordpress is to use $ without defining it, so you need $='jQuery'; before you can use the $ operator to refer to jQuery or substitute the use of $ for the word jQuery. Look up no conflict jQuery for more information.
Another common error in wp ajax and localize script is ajaxurl. For the moment enter in the static value which is www.yourserver.com/wp-admin/admin-ajax.php in most set ups, the wp-admin folder could be somewhere else on your server of course. You should test using console.log(admin_url.ajaxurl); the output will appear in the console mentioned earlier.
Updated code (dont wrap in a function and assign to a variable, just use it as is.
$=jQuery;
$(document).on('click', '#subscribe', function() {
var post_id = $('#postId').val();
$.ajax({
type:"POST",
url: '/wp-admin/admin-ajax.php', // common error is ajax.url undefined (insert your home url into the start of the string, we will eliminate any possibility of mistake by using a static url.
//dataType:"json",
//data : 'action=subscribeOn&post_id='+post_id
data: {
action: 'subscribeOn',
post_id: post_id
},
success: function(data) {
console.log(data); //this writes any output from the server into the console, so if theres a respose you know ajaxurl and jquery is more or less correct, so its good to return something whilst testing...
},
cache: false
});
});
now for the server. When testing you should return something (any data you output using echo var_dump etc will be returned and as we added a command in our browser code to output this to the console we can check for it there.
function subscribeOn() {
global $wpdb, $user_id, $post_id;
$user_id = get_current_user_id();
$post_id = $_POST['post_id'];
// we insert this to test the jQuery settings are correct. if one of the below does not appear in the console, we have issues in jQuery.
if($post_id):
echo $post_id;
else:
echo 'no post id is being submitted check selectors';
endif;
$success= $wpdb->insert("wp_subscribe",
array( 'user_id'=>$user_id, 'post_id'=>$post_id),
array('%s','%s')
);
if($success):
echo 'successfully inserted';
else:
echo 'not inserted, is the table name correct, etc? does the function work elsewhere?';
endif;
}
add_action( 'wp_ajax_nopriv_subscribeOn', 'subscribeOn' );
add_action('wp_ajax_subscribeOn', 'subscribeOn)');
hopefully this will sort it. If it does hit the correct icon beside this answer :)
I found the right way myself. it was just because one bracket after subscribeOn!
add_action('wp_ajax_subscribeOn', 'subscribeOn)');

PHP redirect after form processing

I've been staring at code too long however when I used a simple script to save a form with:
endif;
header('Location: http:/mysite.com/evo/codesaveindex.php');
?>
at the end the page redirected back to itself just fine, however now I have a longer script here I can't quite figure out where or how to code my redirect:
<?php
session_start();
$directory = 'users/'.$_SESSION['username'].'/';
//here you can even check if user selected 'Delete' option:
if($_POST['Action'] == "DELETE"){
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete))
echo $file_to_delete." deleted.";
else
echo "Error deleting file ".$file_to_delete;
}
if($_POST['Action'] == "SAVE"){
// If a session already exists, this doesn't have any effect.
session_start();
// Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
// Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
// This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
// Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
mkdir($USER_DIRECTORY);
endif;
// Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
// Open the text file, write the contents, and close it.
file_put_contents($FILENAME, $_POST['Code']);
endif;
}
?>
may be you should use querystring variable while redirecting.
if($_POST['Action'] == "DELETE") {
$file_to_delete = $_POST['CodeList'];
if(unlink($directory.'/'.$file_to_delete)) {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=1&file='.$file_to_delete);
} else {
header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=0& file='.$file_to_delete);
}
}
In codesaveindex.php:
if(isset($_GET['deleted'])&& $_GET['deleted']==1) {
echo $file_to_delete." deleted.";
} elseif(isset($_GET['deleted'])&& $_GET['deleted']==0) {
echo "Error deleting file ".$file_to_delete;
}
You can't redirect if the page after html has been outputted.
You need to either use output buffering or redirect using javascript,
or organise it so that the redirect happens before the html is shown.
i have a class written for such thing, should be very easy to use class.route.php
simply do this where you want to redirect: route::redirect('page', http_status);

Categories

Resources