Advanced WordPress & PHP: Integration & System Snippets
External Database Connection
Connecting to a database outside of the WordPress installation using the wpdb class.
// Create a new database object for an external server
$external_db = new wpdb( 'db_user', 'db_password', 'db_name', 'db_host' );
// Query the external DB
$results = $external_db->get_results( "SELECT * FROM external_table LIMIT 10" );
// Error checking
if ( $external_db->last_error ) {
error_log( 'DB Error: ' . $external_db->last_error );
}
cURL / Remote Requests (WP_Http)
Using the WordPress wrapper for cURL (more secure and handles timeouts/SSL better).
$url = '[https://api.example.com/v1/data](https://api.example.com/v1/data)';
$args = array(
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Authorization' => 'Bearer ' . $token ),
'body' => array( 'id' => 123, 'status' => 'active' ),
'method' => 'POST'
);
$response = wp_remote_post( $url, $args );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
} else {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
}
Custom Cron Intervals
Adding a custom frequency (e.g., every 5 minutes) to the WP-Cron schedule.
// 1. Add the interval
add_filter( 'cron_schedules', function( $schedules ) {
$schedules['five_minutes'] = array(
'interval' => 300,
'display' => esc_html__( 'Every 5 Minutes' ),
);
return $schedules;
});
// 2. Schedule the event
if ( ! wp_next_scheduled( 'my_custom_five_minute_event' ) ) {
wp_schedule_event( time(), 'five_minutes', 'my_custom_five_minute_event' );
}
// 3. Hook the logic
add_action( 'my_custom_five_minute_event', 'do_my_task' );
File System API
Writing to files using the native WP_Filesystem instead of raw PHP fopen.
global $wp_filesystem;
if ( empty( $wp_filesystem ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
WP_Filesystem();
}
$file_path = WP_CONTENT_DIR . '/uploads/my-log.txt';
$content = "Log entry: " . date('Y-m-d H:i:s') . "\n";
// Append to file
$existing = $wp_filesystem->get_contents( $file_path );
$wp_filesystem->put_contents( $file_path, $existing . $content );