Skip to content

Integration Examples

This guide provides examples of integrating third-party services and APIs with LamaPress.

Table of Contents

API Integrations

Example: REST API Integration

Integrate with external REST APIs:

Create Integration Function:

php
<?php
// functions/api-integration.php

function llFetchApiData($endpoint, $params = []) {
    $url = add_query_arg($params, $endpoint);
    
    $response = wp_remote_get($url, [
        'timeout' => 30,
        'headers' => [
            'Authorization' => 'Bearer ' . get_option('api_token'),
            'Content-Type' => 'application/json',
        ],
    ]);
    
    if (is_wp_error($response)) {
        error_log('API Error: ' . $response->get_error_message());
        return false;
    }
    
    $body = wp_remote_retrieve_body($response);
    return json_decode($body, true);
}

// Cache API responses
function llGetCachedApiData($endpoint, $params = [], $cacheTime = 3600) {
    $cacheKey = 'api_data_' . md5($endpoint . serialize($params));
    $cached = wp_cache_get($cacheKey);
    
    if (false === $cached) {
        $cached = llFetchApiData($endpoint, $params);
        if ($cached) {
            wp_cache_set($cacheKey, $cached, '', $cacheTime);
        }
    }
    
    return $cached;
}

Use in Component:

php
<?php
$apiData = llGetCachedApiData('https://api.example.com/data', [
    'param' => 'value'
]);

if ($apiData) {
    foreach ($apiData['items'] as $item) {
        // Display item
    }
}
?>

Form Integrations

Example: Gravity Forms Integration

Integrate Gravity Forms with components:

ACF Field for Form Selection:

php
<?php
// In component acf.php
$groupFields = [
    [
        'key' => $name . '_01',
        'label' => 'Gravity Form',
        'name' => 'gravity_form',
        'type' => 'select',
        'choices' => [],  // Populated by filter
    ],
];

Populate Form Choices:

php
<?php
// functions/gravity-forms.php
function acf_populate_gf_forms_ids($field) {
    if (class_exists('GFFormsModel')) {
        $choices = [];
        foreach (\GFFormsModel::get_forms() as $form) {
            $choices[$form->id] = $form->title;
        }
        $field['choices'] = $choices;
    }
    return $field;
}
add_filter('acf/load_field/name=gravity_form', 'acf_populate_gf_forms_ids');

Display Form in Component:

php
<?php
$formId = llField('gravity_form', $key, $section);
if ($formId && function_exists('gravity_form')) {
    gravity_form($formId, false, false, false, '', true);
}
?>

Analytics Integrations

Example: Google Tag Manager

Integrate GTM with LamaPress:

Configuration:

php
<?php
// wp-config.php
define('LL_GTM_ID', 'GTM-XXXXXXX');

GTM Scripts:

php
<?php
// components/blocks/layout/head/gtm-js.php
if (defined('LL_GTM_ID') && LL_GTM_ID) {
    ?>
    <!-- Google Tag Manager -->
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','<?= esc_js(LL_GTM_ID) ?>');</script>
    <!-- End Google Tag Manager -->
    <?php
}
?>

Data Layer Integration:

javascript
// Use DataLayer instance
import { app } from '@src/js/core/app'

export default class TrackingComponent {
  trackEvent = (eventName, data) => {
    app.instances.get('datalayer')?.push({
      event: eventName,
      ...data
    })
  }
}

Payment Integrations

Example: Stripe Integration

Integrate Stripe payments:

Create Payment Component:

php
<?php
// components/blocks/payment/index.php
$amount = $fields['amount'] ?? 0;
$description = $fields['description'] ?? '';
?>

<div class="ll-block--payment" data-component="blocks/payment">
    <form id="payment-form" data-amount="<?= esc_attr($amount) ?>">
        <div id="card-element"></div>
        <button type="submit">Pay <?= esc_html($amount) ?></button>
    </form>
</div>

JavaScript Integration:

javascript
import { loadStripe } from '@stripe/stripe-js'

export default class Payment {
  constructor(element) {
    this.element = element
    this.form = this.element.querySelector('#payment-form')
    this.amount = this.form.dataset.amount
    this.init()
  }

  init = async () => {
    this.stripe = await loadStripe('pk_test_...')
    this.bindEvents()
  }

  bindEvents = () => {
    this.form.addEventListener('submit', this.handleSubmit)
  }

  handleSubmit = async (e) => {
    e.preventDefault()
    
    const { error, paymentMethod } = await this.stripe.createPaymentMethod({
      type: 'card',
      card: this.cardElement,
    })
    
    if (error) {
      console.error(error)
      return
    }
    
    // Send to server
    await this.processPayment(paymentMethod.id)
  }

  processPayment = async (paymentMethodId) => {
    const response = await fetch('/wp-json/api/process-payment', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        payment_method_id: paymentMethodId,
        amount: this.amount,
      }),
    })
    
    const result = await response.json()
    // Handle result
  }
}

Social Media Integrations

Example: Instagram Feed

Integrate Instagram feed:

Create Integration Function:

php
<?php
// functions/instagram.php
function llGetInstagramFeed($username, $count = 12) {
    $cacheKey = 'instagram_feed_' . $username;
    $cached = wp_cache_get($cacheKey);
    
    if (false === $cached) {
        // Fetch from Instagram API
        $response = wp_remote_get("https://api.instagram.com/v1/users/{$username}/media");
        $data = json_decode(wp_remote_retrieve_body($response), true);
        
        if ($data && isset($data['data'])) {
            $cached = array_slice($data['data'], 0, $count);
            wp_cache_set($cacheKey, $cached, '', 3600);
        }
    }
    
    return $cached;
}

Display in Component:

php
<?php
$username = llField('instagram_username', $key, $section);
$posts = llGetInstagramFeed($username, 6);

if ($posts) {
    ?>
    <div class="ll-block--instagram-feed">
        <?php foreach ($posts as $post): ?>
            <a href="<?= esc_url($post['link']) ?>" target="_blank">
                <img src="<?= esc_url($post['images']['thumbnail']['url']) ?>" 
                     alt="<?= esc_attr($post['caption']['text'] ?? '') ?>">
            </a>
        <?php endforeach; ?>
    </div>
    <?php
}
?>

Custom Integrations

Example: Custom API Endpoint

Create custom WordPress REST API endpoints:

php
<?php
// functions/api-endpoints.php
add_action('rest_api_init', function() {
    register_rest_route('ll/v1', '/data', [
        'methods' => 'GET',
        'callback' => 'llGetCustomData',
        'permission_callback' => '__return_true',
    ]);
});

function llGetCustomData($request) {
    $data = [
        'items' => get_posts([
            'post_type' => 'custom_type',
            'posts_per_page' => 10,
        ]),
    ];
    
    return new WP_REST_Response($data, 200);
}

Use in JavaScript:

javascript
export default class DataLoader {
  loadData = async () => {
    const response = await fetch('/wp-json/ll/v1/data')
    const data = await response.json()
    return data.items
  }
}

Best Practices

1. Cache API Responses

Always cache API responses:

php
$cacheKey = 'api_data_' . md5($endpoint);
$cached = wp_cache_get($cacheKey);

if (false === $cached) {
    $cached = fetchFromApi();
    wp_cache_set($cacheKey, $cached, '', 3600);
}

2. Error Handling

Always handle errors gracefully:

php
$response = wp_remote_get($url);
if (is_wp_error($response)) {
    error_log('API Error: ' . $response->get_error_message());
    return false;
}

3. Security

Secure API integrations:

  • Store API keys in environment variables
  • Use nonces for form submissions
  • Validate and sanitize all input
  • Escape all output

4. Performance

Optimize integrations:

  • Cache responses
  • Use async loading
  • Minimize API calls
  • Lazy load when possible

Next Steps:

Released under the MIT License.