Performance: Custom endpoint registration
This affects the server response time and client-side loading speed by adding custom REST API endpoints.
<?php add_action('rest_api_init', function () { global $wpdb; register_rest_route('myplugin/v1', '/data/', array( 'methods' => 'GET', 'callback' => function() { // Use transient cache to store results for 5 minutes global $wpdb; $cached = get_transient('myplugin_data_cache'); if ($cached !== false) { return $cached; } $results = $wpdb->get_results("SELECT * FROM large_table"); set_transient('myplugin_data_cache', $results, 300); return $results; }, )); });
<?php add_action('rest_api_init', function () { global $wpdb; register_rest_route('myplugin/v1', '/data/', array( 'methods' => 'GET', 'callback' => function() { // Heavy database queries without caching global $wpdb; $results = $wpdb->get_results("SELECT * FROM large_table"); return $results; }, )); });
| Pattern | Server Processing | Network Transfer | Client Render Delay | Verdict |
|---|---|---|---|---|
| Uncached heavy queries | High CPU and DB load | Longer due to slow response | Delays LCP by 200+ ms | [X] Bad |
| Cached query results | Low CPU and DB load | Faster due to cached data | Improves LCP by 70-90% | [OK] Good |
add_rewrite_endpoint in WordPress?add_rewrite_endpoint is used to add new URL parts to WordPress URLs.add_rewrite_endpoint when registering a custom endpoint?init hook runs early and is the recommended place to add rewrite rules and endpoints.wp_enqueue_scripts is for scripts/styles, admin_menu is for admin menus, and wp_footer runs late in page rendering.add_action('init', function() {
add_rewrite_endpoint('special', EP_PERMALINK | EP_PAGES);
});add_action('init', function() {
add_rewrite_endpoint('promo', EP_ROOT);
});add_download_endpoint adds the endpoint on 'init' hook, which is correct.register_activation_hook to call the endpoint function and then flush rewrite rules ensures flushing happens once on plugin activation.add_action('init', function() {
add_rewrite_endpoint('download', EP_ALL);
flush_rewrite_rules();
}); flushes rules on every page load (bad). function add_download_endpoint() {
add_rewrite_endpoint('download', EP_ROOT);
flush_rewrite_rules();
}
add_action('init', 'add_download_endpoint'); flushes inside init (bad). register_activation_hook(__FILE__, function() {
add_rewrite_endpoint('download', EP_PERMALINK | EP_PAGES);
}); does not flush rules at all.Pass the test and this pattern moves unknown