Categories
Code

Send Gravity Forms Data to Google Spreadsheet or Email

Gravity Forms is an extremely popular Forms plugin for the WordPress. When someone submits a form created with Gravity Forms, the form data is saved inside the MySQL database associated with your WordPress installation. There are paid add-ons through, Zapier for example, that let you do more when someone submits a Form.

For instance, you can setup a task in Zapier that will automatically save the Gravity Form data to a specific Google Spreadsheet. Or you can setup a rule where the data is emailed to you as soon as a form is submitted.

Zapier offers a visual tool to maps your Gravity Forms to Google Spreadsheets but you can do something similar with Google Apps Script and WordPress hooks without needing to subscribe to Zapier. Let me show you how:

From Gravity Forms to Google Spreadsheets

First we need to create a web-app with Google Scripts that will receive the Form data from Gravity Forms and either save it to Google Sheets or send it via Gmail. Also see: Get Google Forms Data in Email.

Open the Google Spreadsheet where you wish to save the Forms data and create a header row with the column names for all the fields that you wish to save from Gravity Forms. Next go to Tools, Script Editor and paste the following snippet.

function doPost(e) {

  if (!e) return;

  var sheetID = "GOOGLE_SPREADSHEET_ID";  // Replace this with the Google Spreadsheet ID
  var sheetName = "Form Responses";       // Replace this with the sheet name inside the Spreadsheet

  var status = {};

  // Code based on Martin Hawksey (@mhawksey)'s snippet

  var lock = LockService.getScriptLock();
  lock.waitLock(30000);

  try {

    var sheet = SpreadsheetApp.openById(sheetID).getSheetByName(sheetName);
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];

    // Add the data and time when the Gravity Form was submitted
    var column, row = [],
      input = {
        "timestamp": new Date()
      };

    for (var keys in e.parameter) {
      input[normalize_(keys)] = e.parameter[keys];
    }

    for (i in headers) {
      column = normalize_(headers[i])
      row.push(input[column] || "");
    }

    if (row.length) {

      sheet.appendRow(row);
      status = {
        result: "success",
        message: "Row added at position " + sheet.getLastRow()
      };

    } else {
      status = {
        result: "error",
        message: "No data was entered"
      };
    }

  } catch (e) {

    status = {
      result: "error",
      message: e.toString()
    };

  } finally {

    lock.releaseLock();

  }

  return ContentService
    .createTextOutput(JSON.stringify(status))
    .setMimeType(ContentService.MimeType.JSON);

}

function normalize_(str) {
  return str.replace(/[^\w]/g, "").toLowerCase();
}

Save the Google Script. Go to the Run menu and choose doPost to authorize the Google Scripts. Next choose Publish, Deploy as web app and save your work. Click Save New Version, set access as Anyone, even anonymous and click Deploy. Make a note of the Google Script URL as we will need it in the WordPress snippet.

From WordPress to Google Spreadsheets

Now we need to write an Action Hook on WordPress side that will send the data to Google Script which will then save the data to Google Spreadsheet. Go your WordPress theme folder and paste this snippet inside your functions.php file.

 rgar($entry, '1'), 'age' => rgar($entry, '2'), 'sex' => rgar($entry, '3'),);

    // Send the data to Google Spreadsheet via HTTP POST request
    $request = new WP_Http();
    $response = $request->request($post_url, array('method' => 'POST', 'sslverify' => false, 'body' => $body));
}
?>

Save the PHP file and submit a test entry. It should show up in your Google Spreadsheet instantly.

Categories
Code

Authenticate WordPress Users with Google Apps Script

You can use the XMLRPC library with Google Scripts to authenticate users that are members of your WordPress or Blogger website.

For instance, if you have a Google Form that you only wish to serve to registered members of your WordPress or BuddyPress website, you can add a layer of authentication before serving the form using the HTML service. This layer will connect to the website through XML RPC to verify if the connecting user is valid or not.

The Google Script can be further customized to only allow users with certain roles -like allow authors and admin but not subscribers. This can be used in conjunction with Easy Digital Downloads to serve files to only users that have the WordPress role as EDD_Subscriber or similar.

function verifyWordPressUser(username, password) {
  
  // Library key: My_8O8KRa_MszCVjoC01DTlqpU7Swg-M5
  
  /* Replace example.com with your WordPress blog URL */
  var wordpressURL = "http://example.com/xmlrpc.php";
  
  /* Call the wp.getUsers API method to get User details */
  var request = new XMLRPC.XmlRpcRequest(wordpressURL, 'wp.getUsers');
  
  /* The first parameter is empty since there's no blog ID for WordPress */
  request.addParam("");   
  request.addParam(username);
  request.addParam(password);
   
  var response = request.send().parseXML();
  
  if (response.faultCode) {
    throw(response.faultString);
  }
  else {
    throw(response[0].display_name  + " is a valid user");
  }
  
}
Categories
Code

Post to WordPress with Google Scripts using XML-RPC API

You can use Google scripts to publish blog posts to any Blogger and WordPress website using the XML-RPC API. The script can be extended to create blog posts by email or you can even send a document from Google Docs and publish it your WordPress as a blog post.

The sample code demonstrates how to create a new post. You need to specify your WordPress site’s XML RPC endpoint, the user name and the password in “plain” text. The blog post may be published as a draft or public by changing the post_status parameter. If the blog post is published successfully, the post ID will be returned else it will return an error string.

To get started, do include the XML RPC library in your Google Apps Script project. The project key for the XML RPC library for Google Apps Script is My_8O8KRa_MszCVjoC01DTlqpU7Swg-M5 – choose the latest version from the dropdown and set the identifier as XMLRPC.

function postToWordPress() {
  
  /* Add your WordPress credentials and replace example.com with your WordPress blog URL */
  var wordpress = {
    url: "http://example.com/xmlrpc.php",
    username: "admin",  
    password: "12345"
  };
  
  /* Make sure your WordPress XML-RPC URL is correct */
  var checkConfig = UrlFetchApp.fetch(wordpress.url, {muteHttpExceptions: true});
  
  if (checkConfig.getResponseCode() !== 200) {
    
    throw new Error("Please check your XML RPC URL");
    
  }
  
  /* Call the metaWeblog.newPost API method to create a new blog post */
  var request = new XMLRPC.XmlRpcRequest(wordpress.url, 'metaWeblog.newPost');
  
  /* The first parameter is empty since there's no blog ID for WordPress */
  request.addParam(""); 
  
  request.addParam(wordpress.username);
  request.addParam(wordpress.password);
  
  /* The blog post content. You can have HTML in the description */
  var blogPost = {
    post_type: 'post',
    post_status: 'publish',  /* Set to draft or publish */
    title: 'post title',
    description: 'post description'
  };
  
  request.addParam(blogPost);
  
  var response = request.send().parseXML();
  
  Logger.log(response);
  
}
Categories
Code

Blogger to WordPress Redirection

The Blogger to WordPress tutorial uses this PHP snippet to redirect visitors on the Blogger blog to the corresponding post on the WordPress site.

When a visitor is redirected from Blogger to WordPress, the blogger slug is contained in the query parameter string. On the WordPress side, this string is parsed and matched against the “blogger_permalink” custom fields on WordPress. If a match if found, the visitor is redirected to the corresponding WordPress post using a 301 redirect.

query_vars['blogger'];
  if ( isset ( $blogger ) ) {
    wp_redirect( labnol_get_wordpress_url ( $blogger ) , 301 );
    exit;
  }
}

add_action( 'template_redirect', 'labnol_blogger_template_redirect' );

function labnol_get_wordpress_url($blogger) {

  /* Extract the blogger slug from the full blogspot.com url */
  if ( preg_match('@^(?:https?://)?([^/]+)(.*)@i', $blogger, $url_parts) ) {

    /* Query the WordPress database to find matching posts */
    $query = new WP_Query ( array ( 
      "meta_key" => "blogger_permalink", "meta_value" => $url_parts[2] ) ); 

    /* if a match is found, get the permalink of the WordPress post */
    if ($query->have_posts()) {
      $query->the_post(); 
      $url = get_permalink(); 
    } 

    wp_reset_postdata(); 

  } 

  /* If permalink is not found, return the blog home page url */
  return $url ? $url : home_url();

}
Categories
Code

404 Page for WordPress with Suggestions

If a visitor mistypes a URL to your WordPress blog or clicks on a link that does not exists, you can show them a more helpful 404 error page that will have suggestions pointing to related articles that they can check out on your WordPress site. Internally, it runs a search using the 404 page URL as the query parameter.

Save this file as 404.php and place it in your WordPress theme folder.



404 Error - Page not found

query_vars['is_search'] = true; $s = str_replace("-", " ", $wp_query->query_vars['name']); $loop = new WP_Query('post_type=any&s=' . $s); ?> have_posts()): ?>

We tried finding the matching pages from our website. Here're some suggestions:

    have_posts()): $loop->the_post(); ?>
Categories
Code

Password Protect your WordPress Admin Folder

WordPress websites and blogs are prone to Brute Force attacks and a recommended way to prevent your site against such attacks is to protect your wp-admin folder with a password. Let me explain.

Your WordPress installation directory has three main folders:

  • the wp-content folder includes all your themes, plugins, images and other uploaded files.
  • the wp-includes folder includes all the PHP functions that actually run WordPress.
  • the wp-admin folder is the front-end for WordPress admin, authors and and other members.

Unlike the public HTML pages and images of your WordPresss website, the Admin dashboard area requires a username and password and is thus accessible only to “authorized” users. However, to make your WordPress more secure, you can add an extra layer of security to the wp-admin folder so that even authorized users can’t just get in with their WordPress passwords.

Secure wp-admin directory of WordPress with a Password

Here’s a step by step guide on how to password protect the wp-admin folder of WordPress. This assumes that you have installed WordPress on a Linux machine with the Apache web server.

Step 1. Log in to your Linux shell and create a new directory that is not accessible from the web. For instance, if your WordPress is installed in /home/peter/example.com/wordpress, you can create a folder as /home/peter/admin (you can give any name).

$ mkdir /home/peter/admin

Step 2. Now we need to specify the username and password that will protect the wp-admin folder. This is independent of your Linux shell user name or your WordPress user.

Run the following command and remember to replace username with another name.

$ htpasswd -c /home/peter/admin/passwords username

Step 3. The above command will create a passwords file inside the /home/peter/admin folder. You can run the “cat” command to view the encrypted htaccess password stored in the passwords file. Next we need to tell Linux to use this password to protect the wp-admin folder.

Go to your WordPress admin folder (at /home/peter/example.com/wordpress/wp-admin/) and create a new .htaccess (use the vi command or create the .htaccess file on your desktop and upload it to wp-admin folder using FTP).

Also see: Improve WordPress Security with Plugins

Step 4. Paste the following text into your new .htaccess file and replace the folder path in Line #3 with your own actual path. Save the changes.

AuthType Basic
AuthName "WordPress Protected Area"
AuthUserFile /home/peter/admin/passwords
Require valid-user
<Files admin-ajax.php>
  Order allow,deny
  Allow from all
  Satisfy any
</Files>
<Files "\.(css|gif|png|js)$">
  Order allow,deny
  Allow from all
  Satisfy any
</Files>

Step 5. Switch to the WordPress root folder (/home/peter/example.com/wordpress), open the .htaccess file for editing and add the following lines outside the #BEGIN WordPress and #END WordPress block.

#Do not display Authorization Error Message
#Instead, redirect to the blog home page
ErrorDocument 401 /

Save the file and you are done. All users of your WordPress (including you) will now have to enter two passwords to access the WordPress Admin dashboard.

See more Linux Commands for WordPress.

Categories
Code

RSS Feed for Podcasts – WordPress Template

You can use your WordPress blog to publish podcasts on iTunes. Most podcasters use FeedBurner to add iTunes specific author information to podcast XML feed but if you prefer to skip FeedBurner, use these feed template.

Create a new page in your WordPress dashboard and give it a custom slug (say podcast). Now create a page-podcast.php file in your WordPress themes folder and copy-paste the following code. Remember to replace information in the highlighted lines.

The permalink of that WordPress Page will become the URL of your Podcast feed which you can now publish to the iTunes Podcasting directory. Here’s a sample Podcast XML feed generated using this RSS template.


/* RSS Feed for iTunes Podcast  */
/* Source: www.labnol.org       */

'; ?>
?>


    
        <? bloginfo_rss('name'); wp_title_rss(); ?>
        
        
        
        no
        
            amit@labnol.org
            Amit Agarwal
        
        Amit Agarwal 
        
        tech, computers, tutorials
        Get the most out of your tech.
        Podcast hosted by Amit Agarwal.
        
            
        
        Creative Commons License        
        25,'tag'=>'podcast')); ?>
        have_posts()) : $q->the_post(); ?>
            
                <? the_title() ?>
                
                
                    
                
                
                    
                
                
                    ]]>
                
                no
                
                
                Amit Agarwal
                computers, tech, tutorials