All Posts

Power CS Charts with Google Sheets

Published: July 22, 2023
Share:
Image

The code below is used to tap into the custom looper functionality within Cornerstone and specifically fetch an external URL for the loop.

// This function hooks into the 'cs_looper_custom_http' filter.
add_filter( 'cs_looper_custom_http', function ( $result, $args ) {
  
  // Retrieve the URL from the $args array or set it to null if not provided.
  $url = isset( $args['url'] ) ? $args['url'] : null;
  
  // If a URL is provided, continue processing.
  if ( $url ) {
  
    // Make an HTTP GET request to the provided URL using WordPress wp_remote_get() function.
    $request = wp_remote_get( $url );
  
    // Check if the HTTP request returned an error.
    if ( ! is_wp_error( $request ) ) {
  
      // Get the response body from the HTTP request and decode it as JSON.
      $response = json_decode( wp_remote_retrieve_body( $request ), true );
  
      // If the response is an array, update the $result with the response data.
      if (is_array( $response ) ) {
        $result = $response;
      }
    }
  }
  
  // Return the modified or unmodified $result back to the filter.
  return $result;
}, 10, 2);

Once you’ve setup your custom looper you’ll set the hook in CS to “http” and then you’ll edit the params for the hook. All you need is the snippet below.

{
  "url":"https://exampleurlforyourapi.com/?path=sheetname"
}

To turn your Google Sheet into an API you can follow the steps found at this article here: https://ravgeetdhillon.medium.com/turn-a-google-sheet-into-a-rest-api-b08f3fd641ad