Write a WordPress code snippet that adds a post Expiration Date for a certain category of post and when the expiration date is passed the post is turned to draft

WPTurbo » Snippets » Write a WordPress code snippet that adds a post Expiration Date for a certain category of post and when the expiration date is passed the post is turned to draft
0

Created with:

Visibility: 

public

Creator: Stephen Oxlade

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

<?php

namespace WPTurbo;

class PostExpiration {

    const EXPIRATION_META_KEY = '_expiration_date';

    // Constructor to initialize actions
    public function __construct() {
        add_action( 'init', [$this, 'check_post_expiration'] ); // Check post expiration on init
        add_action( 'add_meta_boxes', [$this, 'add_expiration_meta_box'] ); // Add a meta box for expiration date
        add_action( 'save_post', [$this, 'save_expiration_date'] ); // Save the expiration date when the post is saved
    }

    // Adds a meta box for the expiration date in the post edit screen
    public function add_expiration_meta_box( $post ) {
        // Check if the post belongs to the specified category
        if ( 'promotions' === get_the_category( $post->ID )[0]->slug ) {
            add_meta_box(
                'expiration_date',
                __('Post Expiration Date', 'wpturbo'), // Title of the meta box
                [$this, 'render_expiration_meta_box'], // Callback function for rendering the box
                null,
                'side',
                'high' // Context and priority for the meta box
            );
        }
    }

    // Renders the meta box for setting the expiration date
    public function render_expiration_meta_box( $post ) {
        $expiration_date = get_post_meta( $post->ID, self::EXPIRATION_META_KEY, true ); // Get the current expiration date
        wp_nonce_field( 'save_expiration_date', 'expiration_date_nonce' ); // Security field for saving data
        echo '<label for="expiration_date">' . __('Expiration Date:', 'wpturbo') . '</label>'; // Label for the input
        echo '<input type="date" id="expiration_date" name="expiration_date" value="' . esc_attr( $expiration_date ) . '" />'; // Date input for setting the expiration date
    }

    // Saves the expiration date when the post is saved
    public function save_expiration_date( $post_id ) {
        // Verify nonce for security
        if ( ! isset( $_POST['expiration_date_nonce'] ) || ! wp_verify_nonce( $_POST['expiration_date_nonce'], 'save_expiration_date' ) ) {
            return; // Exit if verification fails
        }

        // Check if the expiration date is set and save it
        if ( isset( $_POST['expiration_date'] ) ) {
            update_post_meta( $post_id, self::EXPIRATION_META_KEY, sanitize_text_field( $_POST['expiration_date'] ) ); // Save the sanitized expiration date
        }
    }

    // Checks for expired posts and updates their status
    public function check_post_expiration() {
        $args = [
            'category_name' => 'YOUR_CATEGORY_SLUG', // Target category slug
            'post_status' => 'publish', // Only published posts
            'posts_per_page' => -1, // Retrieve all posts
        ];

        $posts = get_posts( $args ); // Get posts based on the query

        // Loop through each post to check for expiration
        foreach ( $posts as $post ) {
            $expiration_date = get_post_meta( $post->ID, self::EXPIRATION_META_KEY, true ); // Get the expiration date

            // Check if the expiration date has passed
            if ( ! empty( $expiration_date ) && strtotime( $expiration_date ) < time() ) {
                // Set the post status to draft if expired
                $post->post_status = 'draft';
                wp_update_post( $post ); // Update the post status in the database
            }
        }
    }
}

new PostExpiration(); // Instantiate the class
				

These comments will help other developers (or yourself in the future) understand the code's functionality without having to decipher the logic from scratch.

Register an account to save your snippets or go Pro to get more features.