Thursday, June 22, 2023

FirebaseApp to Connect Google Apps Script with Firebase Realtime Database

FirebaseApp is a GitHub project by Romain Vialard that provides a Google Apps Script binding for the Firebase Realtime Database. This means that you can use Apps Script to interact with Firebase Realtime Database from within Google Sheets, Docs, Slides, and other Google Apps.

The FirebaseApp project is still under development, but it already includes a number of useful features, including:

  • The ability to create, read, update, and delete Firebase Realtime Database records.
  • The ability to listen for changes to Firebase Realtime Database records.
  • The ability to send push notifications to Firebase Realtime Database users.

The FirebaseApp project is a valuable resource for anyone who wants to use Firebase Realtime Database from within Google Apps Script. It is well-documented and easy to use, and it is constantly being updated with new features.

Here are some of the benefits of using FirebaseApp:

  • It allows you to use Firebase Realtime Database from within Google Apps, which can save you time and effort.
  • It is a well-documented and easy-to-use project.
  • It is constantly being updated with new features.

If you are interested in using Firebase Realtime Database from within Google Apps Script, I encourage you to check out the FirebaseApp project. It is a valuable resource that can help you save time and effort.


Install:

Best it to copy the content of this file in your Google Apps Script. 
Get project filehttps://github.com/RomainVialard/FirebaseApp/blob/master/src/Code.gs


You can also add it as a library, though this is not recommended.
Check here to add library https://developers.google.com/apps-script/guides/libraries 
Use this Library's script ID to add: 1VlYLzhwx0YEoxIe62eItLAZeobVt_l-GQUKt2MXXuBHFVsqBkl9C_yBB

 

Use: 

Need to use it your Firebase project Database URL (looks like  https://{your-project}.firebaseio.com/) & App Secret key.  

// Get the FirebaseApp object.

var firebaseApp = FirebaseApp.getDatabaseByUrl("https://my-project.firebaseio.com/"); 


An example :


function writeDataToFirebase() {
  // Get the FirebaseApp object.
  var firebaseApp = FirebaseApp.getDatabaseByUrl("https://my-project.firebaseio.com/");

  // Create a new record in the Firebase Realtime Database.
  var record = firebaseApp.database().ref("/my-record").set({
    name: "John Doe",
    age: 30,
  });

  // Listen for changes to the Firebase Realtime Database record.
  var listener = firebaseApp.database().ref("/my-record").on("value", function(snapshot) {
    // Do something with the updated record.
  });
} 

This code first gets the FirebaseApp object by specifying the URL of the Firebase Realtime Database. Then, it creates a new record in the Firebase Realtime Database and sets the name and age of the record. Finally, it listens for changes to the Firebase Realtime Database record.

To run this code, you would need to save it as a Google Apps Script project and then run it from within a Google Spreadsheet. For more information on how to do this, please see the Google Apps Script documentation: https://developers.google.com/apps-script/.

Here is another example code that shows how to use FirebaseApp to send push notifications to Firebase Realtime Database users:

function sendPushNotification() {
  // Get the FirebaseApp object.
  var firebaseApp = FirebaseApp.getDatabaseByUrl("https://my-project.firebaseio.com/");

  // Get the list of users who are subscribed to push notifications.
  var users = firebaseApp.database().ref("/users").list();

  // Send a push notification to all users.
  users.forEach(function(user) {
    var notification = firebaseApp.notifications().create(user.key, {
      title: "New notification",
      body: "This is a new notification.",
    });
    notification.send();
  });
}
This code first gets the FirebaseApp object and then gets the list of users who are subscribed to push notifications. Then, it sends a push notification to all users. 


Here are some additional resources that you may find helpful:


Wednesday, March 17, 2021

How to Quickly and Easily Sort Woocommerce Products According to SKUs on the Admin Listing Page


If you're running a WooCommerce store with a large number of products, sorting them be a daunting task. However, with this code, you can quickly and easily sort your products according to their SKUs on the admin listing page. This means you can easily find and manage your products based on their unique identifiers. The code works by adding custom order by arguments and filters to the query, allowing you to sort your products in ascending or descending order based on their SKUs. With this code, you can save time and streamline your product management process, making it easier to run your online store.

/**
* Sort by SKU on admin listing page
*/
add_filter( 'request', 'orderby_sku_request_query', 9999 );
function orderby_sku_request_query($query_vars) {
    global $typenow;
    
    // remove filter on load if already added otherwise these applied again & again
    remove_filter( 'posts_clauses', 'orderby_sku_desc_post_clauses', 9999 );
    remove_filter( 'posts_clauses', 'orderby_sku_asc_post_clauses', 9999 );

    // Custom order by arguments.
    if ( 'product' === $typenow && isset( $query_vars['orderby'] ) && 'sku' === strtolower( $query_vars['orderby'] ) ) {
        $order = isset( $query_vars['order'] ) ? strtoupper( $query_vars['order'] ) : 'DESC';
        $callback = 'DESC' === $order ? 'sort_products_by_sku_desc' : 'sort_products_by_sku_asc';
        add_filter( 'posts_clauses', $callback, 9999 );
    }
    return $query_vars;
}

/**
* In assending order, keep whitespace in sql query
*/
function sort_products_by_sku_asc( $args ) {
    $args['orderby'] = ' CAST(wc_product_meta_lookup.sku AS UNSIGNED) ASC, wc_product_meta_lookup.product_id ASC ';
    return $args;
}

/**
* In dessending order, keep whitespace in sql query
*/
function sort_products_by_sku_desc( $args ) {
    $args['orderby'] = ' CAST(wc_product_meta_lookup.sku AS UNSIGNED) DESC, wc_product_meta_lookup.product_id DESC ';
    return $args;
}



Here's a line-by-line breakdown of how the above code works:

  • The code starts by adding a filter to the 'request' hook, which allows you to modify the query variables for the current request.

  • The function 'orderby_sku_request_query' is called, which removes any existing filters that may interfere with the sorting process.

  • The function checks if the current post type is 'product', which is the default post type for WooCommerce products.

  • If the post type is 'product', the function checks if the 'orderby' query variable is set.

  • If the 'orderby' query variable is set, the function checks if it is set to 'sku', which is the field we want to sort by.

  • If the 'orderby' query variable is set to 'sku', the function determines whether to sort in ascending or descending order based on the 'order' query variable.

  • The function then adds a filter to the 'posts_clauses' hook, which allows you to modify the SQL query used to retrieve the posts.

  • The filter callback function 'orderby_sku_asc_post_clauses' is called if the sort order is ascending, or 'sort_products_by_sku_desc' if the sort order is descending.

  • The 'sort_products_by_sku_asc' function modifies the 'orderby' argument of the SQL query to sort by the 'sku' field in ascending order, followed by the 'product_id' field in ascending order.

  • The 'sort_products_by_sku_desc' function modifies the 'orderby' argument of the SQL query to sort by the 'sku' field in descending order, followed by the 'product_id' field in descending order.

  • The modified SQL query is then used to retrieve the sorted products, which are displayed on the admin listing page.

  • Overall, this code provides a simple and efficient way to sort WooCommerce products according to their SKUs, making it easier to manage your online store.

Wednesday, November 11, 2020

Revamp User Profiles on the Admin Panel with Custom Contact Fields in WordPress using the "user_contactmethods" Filter

With the user_contactmethods filter, you can easily enhance the contact information fields available to your WordPress users. This filter allows you to edit the available contact methods on a user's profile page, including adding and removing fields. By customizing the contact fields, you can provide a more personalized experience for your users.

To get started, simply use the user_contactmethods filter and pass an associative array of the contact fields you want to add or remove. For example, you can add fields for Skype and Twitter usernames, or remove fields for user's Aim.

Here's an example code snippet that demonstrates how to use the user_contactmethods filter:

Parameters

  1. array $user_contact : an associative array
  2. WP_User $user: WP_User object or null if none was provided.
  3. Code Example Below: 
add_filter( 'user_contactmethods', 'modify_user_contact_methods' );
function modify_user_contact_methods( $user_contacts ) {
    // Add user contact methods
    $user_contacts['skype']  = __( 'Skype Username', 'text-domain' ); 
    $user_contacts['twitter'] = __( 'Twitter Username', 'text-domain' ); 

    // Remove user contact methods
    unset( $user_contacts['aim'] );

    return $user_contacts;
}
          

By using this filter, you can easily customize the contact fields available to your users and provide a more personalized experience on your WordPress site.


Reference

  1. https://codex.wordpress.org/Plugin_API/Filter_Reference/contactmethods 
  2. https://developer.wordpress.org/reference/functions/wp_get_user_contact_methods/

Thursday, July 2, 2020

Optimize Your Website with These Simple Code Snippets and stop 3rd Party Scripts On Google page speed insights

To stop 3rd party scripts from running on Google PageSpeed Insights use this code:

 <?php

// Stop 3rd party scripts on Google PageSpeed Insights
if (isset($_SERVER['REMOTE_ADDR']) && strpos($_SERVER['REMOTE_ADDR'], '66.249.82') === false ) :
?>
<!-- Write your code here -->
<?php endif ?>

It checks if the user's IP address is not from Google's crawler and only executes the code if the condition is true. This can help improve your website's page speed score on Google PageSpeed Insights by preventing unnecessary scripts from running during the analysis.

To use this code, simply add it to your website's header or footer. You can add your own code inside the <!-- Write your code here --> comment.

By implementing this code, you can optimize your website's performance and improve your page speed score on Google PageSpeed Insights.


To speed up the loading of Google Fonts, use the preload attribute with the link tag. Here's an example code snippet that demonstrates this optimization technique using the pre HTML tag:

<link rel="preload" href="//fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&family=Poppins:wght@300;400;500;600;700&display=swap" as="style" onload="this.onload=null;this.rel='stylesheet'" />


 

Saturday, June 13, 2020

Set Media Attribute In All Styles to Improve Your Website's Page Speed with One Simple JavaScript Code

Are you looking for ways to improve your website's page speed and performance? Look no further than this simple JavaScript code that can make a big impact on your site's speed.

<script>
    // Set media attribute to "all" for all stylesheets
    const stylesheets = document.querySelectorAll('link[rel="stylesheet"]');
    stylesheets.forEach(stylesheet => {
        stylesheet.media = 'all';
    });
</script>

The code sets the media 
attribute of all stylesheets to "all", which can improve page speed on Google PageSpeed Insights. By doing this, the browser can load all stylesheets at once, instead of waiting for them to load one by one. This can significantly reduce the time it takes for your website to load, which can improve user experience and search engine rankings.
 
To implement this code, simply add it to the end of your page, right before the closing body tag. The code uses modern JavaScript syntax, making it more efficient and easier to read than older JavaScript code.

By improving your website's page speed, you can engage visitors and keep them on your site longer. Slow-loading websites can lead to high bounce rates and lost revenue. With this simple JavaScript code, you can improve your website's performance and provide a better user experience for your visitors.

Try implementing this code on your website today and see the difference it can make in your page speed and overall performance.

Tuesday, June 2, 2020

WordPress Custom Login Form via Ajax

Create & implement custom login form via Ajax to give user login feature. Here I have developed for this a shortcode so easily put this code in any files (in theme functions.php, plugin's file) and can placed shortcode in any template file, sidebar file, page content, post content, widget.

Here I have used only 'wp_ajax_nopriv_' action hook to accept ajax request because 'wp_ajax_nopriv_' action hook is accept only requests are send via frontend pages (non-logged in users).

# Create a shortcode [login_form] so we can put it wherever we want
# and this put functions.php or your desire plugin

add_shortcode('login_form', 'pkt_login_form');
function pkt_login_form($attr) {
	/* define desire key index */
    $attr = shortcode_atts( array(
		
	), $attr );

    extract($attr);

    ob_start();
    require 'login.php';
    $return = ob_get_clean();
	return $return;
}


# here login.php page code 
<form action="" id="login_form" method="POST">
    <input name="pkt_login" type="hidden" value="1" />
        

    <div class="form-check">
        <label>Email Address</label>
        <input name="email" placeholder="Your registered email address" required="" type="email" />
    </div>

    <div class="form-check">
        <label>Password</label>
        <input name="password" required="" type="password" />
    </div>

    <div class="form-check">
        <input class="form-check-input" name="remember" type="checkbox" value="1" />
        <label>Keep me logged in</label>
        <a href="&lt;?php echo home_url('wp-login.php?action=lostpassword') ?&gt;" id="forget_pass_btn">Forget Password?</a>
    </div>
    <div class="btn_mainstyle">
        <button class="btn_style btn_submit" type="submit">Log in</button>
        &nbsp;
        <span class="spinner-border text-primary" style="display: none; height: 20px; width: 20px;"></span>
    </div>
</form>


<script>
	jQuery('#login_form').submit(function (e) {
		e.preventDefault();
		let th = jQuery(this);
		let data = th.serialize();
		th.find('.btn_mainstyle span').show()
		jQuery('.response-msg').text('').hide()
		jQuery('.btn_submit').attr('disabled', true)

		jQuery.ajax({
			url: '<?php echo admin_url('admin-ajax.php') ?>',
			type: 'POST',
			dataType: 'json',
			data: {
				action: 'pkt_login',
				data: data
			},
			success: function (res) {
				th.find('.btn_mainstyle span').hide();
				jQuery('.response-msg').html(res.msg).show();

				if (res.status) {
					jQuery('.response-msg').removeClass('text-danger').addClass('text-success');
					setTimeout(() => {
						window.location.href = res.redirectTo;
					}, 1500);
				} else {
					jQuery('.response-msg').removeClass('text-success').addClass('text-danger');
					jQuery('.btn_submit').attr('disabled', false)
				}

			},
			error: function (x, h) {
				console.log(x, h);
				th.find('.btn_mainstyle span').hide();
				jQuery('.response-msg').html('An error has occured during Login')
					.show().addClass('text-danger');
				jQuery('.btn_submit').attr('disabled', false)
			}
		});
		return false;
	});
</script>



# now add a ajax handler to receive ajax request
# here need to use only 'wp_ajax_nopriv_' action 

add_action('wp_ajax_nopriv_pkt_login', 'pkt_login');
function pkt_login() {
	$response = ['status' =&gt; false];
	if (empty($_POST['data']))
		$response['msg'] = 'Please flll out the form!!';
	else {
		parse_str($_POST['data'], $data);
		if (! wp_verify_nonce( $data['pkt_form_nonce'], 'pkt_nonce' )) {
			$response['msg'] = 'Our Site is protected!!';

		} else {
			$user_email = sanitize_email($data['email']);
			$password = $data['password'];

			if (! is_email( $user_email ) ) {
				$response['msg'] = 'Error: The email address isn&#8217;t correct. or already registered.';

			} elseif (!email_exists( $user_email )) {
				$response['msg'] = 'Error: The email address is not registered.';

			} else {
				$creds = array(
					'user_login'    =&gt; $user_email,
					'user_password' =&gt; $password,
					'remember'      =&gt; empty($data['remember']) ? false : true
				);

				$user = wp_signon( $creds, true );
				if ( is_wp_error( $user ) ) {
					$response['msg'] = $user-&gt;get_error_message();
				} else {
					$response['status'] = true;
					$response['redirectTo'] = site_url();
					$response['msg'] = 'Login successfully.';
				}
			}
		}
	}
	echo json_encode($response);
	wp_die();
}

Tuesday, April 14, 2020

Convert user time to UTC time


/**
 * Convert user's local time to UTC time
 */
function dateTime_local_to_utc($time, $timezone, $abbr = false) {
    //target time zone
    if ($abbr) {
        $t = timeStandardToTimeZone($timezone);
        $timezone = $t['timezone_id'];
    }

    $userTimezone = new DateTimeZone($timezone);
    $userTime = new DateTime('now', $userTimezone);

    // time in seconds, based on UTC
    $offset = $userTime->getOffset();

    // get server timeZone first
    $server_timezone = date_default_timezone_get();
    // set server timeZone provided via user
    date_default_timezone_set($timezone);

    // get UTC time
    $time = date('Y-m-d H:i:s', strtotime($time) - $offset);

    // now set server timeZone default
    date_default_timezone_set($server_timezone);
    return $time;
}

if (!function_exists('timeStandardToTimeZone')) {
    function timeStandardToTimeZone($ts)
    {
        $timezone_abbreviations = DateTimeZone::listAbbreviations();
        if (!empty($timezone_abbreviations[strtolower($ts)])) {
            return $timezone_abbreviations[strtolower($ts)][0];
        }

        return $ts;
    }
}