星期五 , 6 6 月 2025

WP怎样实现ajax或者rest api的url 动态化

Here are the different methods to make your fetch URL dynamic:

Method 1: Auto-detect Current Domain (Recommended for most cases)

javascriptconst apiUrl = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}/wp-json/wp/v2/domain`;

Method 2: Environment-based Configuration

Perfect for development/staging/production environments:

javascriptconst CONFIG = {
    development: 'http://domain.test/wp-json/wp/v2/domain',
    production: 'https://yourdomain.com/wp-json/wp/v2/domain'
};

Method 3: WordPress Integration (Best for WordPress themes/plugins)

Add to your functions.php:

phpwp_localize_script('your-script', 'apiSettings', array(
    'apiUrl' => home_url('/wp-json/wp/v2/domain')
));

Method 4: HTML Data Attributes

Add to your HTML:

html<div id="app" data-api-url="http://domain.test/wp-json/wp/v2/domain"></div>

Method 5: Quick Fix for Your Current Code

Fixed WordPress Domain Fetcher

Code ∙ Version 2 

// Dynamic API URL – automatically uses current domain const apiUrl = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ‘:’ + window.location.port : ”}/wp-json/wp/v2/domain`; // Fetch domain posts and transform data

Choose the method that best fits your use case:

  • Method 1 (auto-detect) – Works great if your JavaScript runs on the same domain as WordPress
  • Method 2 (environment config) – Perfect for multiple environments
  • Method 3 (WordPress integration) – Best if you’re building a WordPress theme/plugin
  • Method 4 (data attributes) – Good for flexibility without code changes
  • Method 5 (quick fix) – Simplest solution for immediate use

The updated code now automatically detects your current domain and constructs the API URL dynamically, so it will work on domain.test, localhost, your production domain, or any other domain without changing the code.

Check Also

@wordpress/create-block 创建多个block框架教程

如果只转移的话带有packag …

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注