如何通过WordPress及Boldgrid插件访问Cloud Firestore?
Hey there! No worries about not being an HTTP expert—let’s walk through this step by step for your BoldGrid-powered WordPress site. I’ll keep this beginner-friendly so you can get up and running quickly:
First, you’ll need to get your Firebase environment ready:
- Head to the Google Cloud Console, create or select your project, then enable Cloud Firestore. Start with test mode for simplicity (you can tighten security rules later).
- Generate a service account key: Go to IAM & Admin > Service Accounts, create a new service account, assign it the
Cloud Datastore Userrole, then create and download the JSON key file. Store this file somewhere not publicly accessible (like outside your WordPress web root—never put it inwp-content/uploadsor similar, since that’s web-readable).
Since WordPress runs on PHP, we’ll use the official Firebase PHP SDK:
- If your server supports Composer, run this command in your WordPress root directory:
composer require kreait/firebase-php kreait/firebase-tokens - If Composer isn’t an option, download the pre-built SDK package, unzip it into a secure folder (like your BoldGrid theme’s
incdirectory), then add this to your theme’sfunctions.phpto load it:require_once get_stylesheet_directory() . '/inc/firebase-php/vendor/autoload.php'; - Initialize Firebase in
functions.php:use Kreait\Firebase\Factory; use Kreait\Firebase\ServiceAccount; // Load your service account key (update the path to match where you stored your JSON file) $serviceAccount = ServiceAccount::fromJsonFile('/path/to/your/service-account-key.json'); // Set up Firestore connection $firebase = (new Factory)->withServiceAccount($serviceAccount)->create(); global $firestoreDb; $firestoreDb = $firebase->getFirestore()->database();
Now let’s fetch data from Firestore. For example, if you have a products collection, here’s how to pull all documents:
// Access the "products" collection $productsCollection = $firestoreDb->collection('products'); // Get all documents in the collection $documents = $productsCollection->documents(); // Store results in an array to use later $firestoreProducts = []; foreach ($documents as $doc) { if ($doc->exists()) { $firestoreProducts[] = [ 'id' => $doc->id(), 'details' => $doc->data() ]; } }
Want a filtered query? Try fetching only in-stock products:
$query = $productsCollection->where('in_stock', '=', true)->orderBy('price'); $documents = $query->documents();
There are two easy ways to show this data:
Option 1: Use a Custom Shortcode
Add this to functions.php to create a shortcode you can drop into any page/post:
add_shortcode('display_firestore_products', function() { global $firestoreDb; $productsCollection = $firestoreDb->collection('products'); $documents = $productsCollection->documents(); $output = '<div class="firestore-products">'; foreach ($documents as $doc) { if ($doc->exists()) { $product = $doc->data(); // Escape content to avoid security issues $output .= sprintf( '<div class="product-card"><h3>%s</h3><p>Price: $%s</p><p>%s</p></div>', esc_html($product['name']), esc_html($product['price']), esc_html($product['description']) ); } } $output .= '</div>'; return $output; });
Then in BoldGrid’s page editor, add a "Shortcode" block and paste [display_firestore_products] to see your data.
Option 2: Embed Directly in a Theme Template
If you want data on a specific page (like a custom product page), edit your BoldGrid theme’s template file (e.g., page-products.php) and add:
<?php global $firestoreDb; $productsCollection = $firestoreDb->collection('products'); $documents = $productsCollection->documents(); ?> <section class="firestore-products-section"> <?php foreach ($documents as $doc): ?> <?php if ($doc->exists()): ?> <?php $product = $doc->data(); ?> <article class="product-item"> <h2><?php echo esc_html($product['name']); ?></h2> <p><?php echo esc_html($product['description']); ?></p> <span class="price">$<?php echo esc_html($product['price']); ?></span> </article> <?php endif; ?> <?php endforeach; ?> </section>
- Protect your service account key: Never expose the JSON file to the web. For extra safety, store its contents as a WordPress constant in
wp-config.phpand load it withServiceAccount::fromValue(getenv('FIREBASE_SERVICE_ACCOUNT')). - Update Firestore security rules: Once you’re done testing, switch from test mode to rules that restrict access (e.g., only allow authenticated users to read data, or limit writes to specific roles).
- Cache query results: Firestore API calls add latency and cost. Use WordPress’s built-in caching with
wp_cache_set()andwp_cache_get()to store results for 15-30 minutes, like:$cachedProducts = wp_cache_get('firestore_products'); if (!$cachedProducts) { // Run your Firestore query here wp_cache_set('firestore_products', $firestoreProducts, '', 1800); // Cache for 30 minutes } else { $firestoreProducts = $cachedProducts; }
内容的提问来源于stack exchange,提问作者Tord Larsen

