Log File Creation WordPress

User
create and update txt log file if exist in wordpress on some occasion custom code
Assistant
To create and update a text log file in WordPress when a specific event occurs, you can use the following custom code. This example assumes you want to log a message when a specific action is triggered, such as when a post is published. You can modify the action and log message according to your needs.

### Step 1: Create a Custom Function

Add the following code to your theme's `functions.php` file or create a custom plugin.

function log_to_file($message) {
    // Define the log file path
    $log_file = WP_CONTENT_DIR . '/logs/custom-log.txt';

    // Create the logs directory if it doesn't exist
    if (!file_exists(dirname($log_file))) {
        mkdir(dirname($log_file), 0755, true);
    }

    // Format the log message
    $timestamp = current_time('Y-m-d H:i:s');
    $formatted_message = "[$timestamp] $message" . PHP_EOL;

    // Write to the log file
    file_put_contents($log_file, $formatted_message, FILE_APPEND | LOCK_EX);
}

// Hook the function to an action (e.g., when a post is published)
add_action('publish_post', function($post_ID) {
    $post_title = get_the_title($post_ID);
    log_to_file("Post published: $post_title (ID: $post_ID)");
});

### Explanation of the Code

1. **Function `log_to_file($message)`**:
– Defines the log file path in the `wp-content/logs/` directory.
– Checks if the `logs` directory exists; if not, it creates it.
– Formats the log message with a timestamp.
– Appends the log message to the log file.

2. **Action Hook**:
– The example hooks the logging function to the `publish_post` action. You can replace `publish_post` with any other action or event you want to log.

### Step 2: Check the Log File

After you publish a post (or trigger the specified action), you can check the `custom-log.txt` file located in the `wp-content/logs/` directory for the log entries.

### Note
– Ensure that the server has write permissions to the `logs` directory.
– If the directory or file does not exist, the script will create them, but permissions might need to be set correctly.
– Modify the action and message to suit your specific use case.

Leave a Comment

Your email address will not be published. Required fields are marked *