首页 WordPress教程 WP怎样实现ajax或者rest api的url 动态化

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

作者 WP导师

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.

您可能还喜欢

发表评论