Table of Contents
What do you need
Setting plugin
Create Meta Box
Use add_meta_box() to display the meta box
Create callback function
Save data after saving
添加随机数以确保安全
添加 JQuery UI 日期选择器
修改查询以排除过期帖子
摘要
Home Web Front-end HTML Tutorial Add expiration date to WordPress posts

Add expiration date to WordPress posts

Sep 10, 2023 pm 12:25 PM
wordpress Expiration date Post

I run a few websites that include notifications and important information in a banner on their home page. I tend to use a custom post type for this, add banners and display them where needed in the theme. (If you want to do something similar, it's explained in this tutorial.)

But my banners always have an expiration date. For example, they may contain information about upcoming events or job vacancies. Once the event ends or the vacancy is filled, I have to go into the website and delete the post manually.

It would be much easier if when creating such posts I could give them an expiration date so they would no longer be visible on my site.

In this tutorial I will show you how to do this. There are three steps:

  1. Create a meta box for the expiration date in the post edit screen.
  2. Apply the jQuery UI date picker to the meta box field to enhance the interface.
  3. Finally, use the pre_get_posts hook to ensure that posts with an expired date are not displayed.

What do you need

To complete this tutorial you will need:

  • Development Installation of WordPress
  • Code Editor

You will create a plugin with all the code required for the expiration date and activate it on your website. So let’s get started!

Setting plugin

First you need to create the plugin. In the plugins folder of the wp-content directory, create an empty file named tutsplus-post-expiry-date-php.

Open the file in the code editor and add the following content to it:

<?php
/*
Plugin Name: Add an Expiry Date to Posts
Plugin URI: https://.tutsplus.com/tutorials/add-an-expiry-date-to-wordpress-posts--cms-22665
Description: Adds an expiry date to posts, using a the jQuery UI datepicker
Author: Rachel McCollin
Version: 1.0
 */
Copy after login

You will need to edit this file to use your own name and plugin URL, but that’s all you need to tell WordPress that this is a plugin and what it does.

Now go to the Plugins screen in WordPress admin and activate the plugin.

Create Meta Box

First we will create the meta box for the expiration date.

Use add_meta_box() to display the meta box

The first step is to create the function that adds the meta box to the post edit screen. Add this to your plugin file:

function tutsplus_add_expiry_date_metabox() {
    add_meta_box( 
        'tutsplus_expiry_date_metabox', 
        __( 'Expiry Date', 'tutsplus'), 
        'tutsplus_expiry_date_metabox_callback', 
        'post', 
        'side', 
        'high' 
    );
}
add_action( 'add_meta_boxes', 'tutsplus_add_expiry_date_metabox' );
Copy after login

This uses the add_meta_box() function, which has six parameters:

  • 'tutsplus_expiry_date_metabox': The unique ID of this metabox
  • __( 'Expiry Date', 'tutsplus'): This is displayed as the title of the meta box

  • 'tutsplus_expiry_date_metabox_callback': The callback function that will populate the metabox (we will create it next)

  • 'post': The post type

    for which this meta box will appear on the edit screen

  • 'side': Which part of the screen the meta box will appear on

  • 'high': Where the meta box will appear

Then attach the function to the add_meta_boxes hook so that it fires at the correct time.

Create callback function

If you save the plugin now and load the edit screen, you will see an error because the callback function has not been defined yet. So that's what we're going to do next.

Add this to your plugin file:

function tutsplus_expiry_date_metabox_callback( $post ) { ?>
    
	<form action="" method="post">
		
		<?php 		
		//retrieve metadata value if it exists
		$tutsplus_expiry_date = get_post_meta( $post->ID, 'expires', true );
		?>
		
		<label for "tutsplus_expiry_date"><?php __('Expiry Date', 'tutsplus' ); ?></label>
				
		<input type="text" class="MyDate" name="tutsplus_expiry_date" value=<?php echo esc_attr( $tutsplus_expiry_date ); ?> / >			
	
	</form>
	
<?php }
Copy after login

Let’s see what it does:

  • It defines the tutsplus_expiry_date_metabox_callback() callback function, with $post as its object.
  • It opens a form element.
  • It will create a variable named $tutsplus_expiry_date with the value of the 'expires' meta key as its value.
  • It creates a label for the field in the meta box.
  • It creates an input element with the name tutsplus_expiry_date using the MyDate class required for the date picker to work, which we will use later when saving the field data, and the value$tutsplus_expiry_date.
  • It closes the form.

Now we have the form, but it won't actually do anything unless we create another function to hold the data the user adds to it.

Save data after saving

To save any data input to the form, we need to create a function and then attach it to the save_post hook.

In your plugin file, add the following:

function tutsplus_save_expiry_date_meta( $post_id ) {
    
	// Check if the current user has permission to edit the post. */
	if ( !current_user_can( 'edit_post', $post->ID ) )
    return;
	
	if ( isset( $_POST['tutsplus_expiry_date'] ) ) {		
		$new_expiry_date = ( $_POST['tutsplus_expiry_date'] );
		update_post_meta( $post_id, 'expires', $new_expiry_date );		
	}
	
}
add_action( 'save_post', 'tutsplus_save_expiry_date_meta' );
Copy after login

This does the following:

  • 它检查当前用户是否具有当前帖子的 edit_post 能力。
  • 如果是,它会使用 isset 检查数据是否已添加到元框字段。
  • 如果是这种情况,它会创建一个名为 $new_expiry_date 的变量,并将其定义为输入的值。
  • 最后,它会使用该值更新帖子的元数据。

所以我们现在有一个元框,它可以让用户添加文本并将其保存到帖子元数据中。让我们让它更安全。

添加随机数以确保安全

为了确保帖子元数据仅通过此表单进行编辑,我们将添加一个随机数。

在回调函数中,在函数的其余内容之前,添加以下代码:

wp_nonce_field( 'tutsplus_expiry_date_metabox_nonce', 'tutsplus_nonce' );
Copy after login

接下来,在用于保存数据的 tutsplus_save_expiry_date_meta() 函数中,在函数开头添加以下内容:

if( !isset( $_POST['tutsplus_nonce'] ) ||
    !wp_verify_nonce( $_POST['tutsplus_nonce'],
	'tutsplus_expiry_date_metabox_nonce'
	) ) 
return;
Copy after login

现在保存您的插件并查看您的帖子编辑屏幕。您将看到您的元框:

Add expiration date to WordPress posts

这是一个好的开始,但问题是目前这是一个普通的文本字段,所以没有办法确保您的用户仅以正确的格式输入日期。我们将通过添加 jQuery UI 日期选择器来纠正这个问题。

添加 JQuery UI 日期选择器

好消息是 jQuery UI 日期选择器预装了 WordPress,因此您无需注册或安装它:只需将其放入函数中即可。

在插件文件的顶部添加以下内容:

function tutsplus_load_jquery_datepicker() {    
	wp_enqueue_script( 'jquery-ui-datepicker' );
	wp_enqueue_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' );
}
add_action( 'admin_enqueue_scripts', 'tutsplus_load_jquery_datepicker' );
Copy after login

这会将脚本本身和存储在 Google API 上的脚本样式表排入队列。请注意,您必须将其挂钩到 admin_enqueue_scripts 操作挂钩,而不是像在前端使用脚本时那样挂钩到 wp_enqueue_scripts

接下来,您需要将脚本添加到输出表单的回调函数中。在 input 元素之后和结束 </form> 标记之前,添加以下内容:

<script type="text/javascript">
    jQuery(document).ready(function() {
		jQuery('.MyDate').datepicker({
			dateFormat : 'dd-mm-yy'
		});
	});
</script>			
Copy after login

这引用了您已添加到输入元素的 MyDate 类,并向其中添加了日期选择器脚本。

您的回调函数现在将如下所示:

function tutsplus_expiry_date_metabox_callback( $post ) { ?>
    
	<form action="" method="post">
		
		<?php 		
		// add nonce for security
		wp_nonce_field( 'tutsplus_expiry_date_metabox_nonce', 'tutsplus_nonce' );
		
		//retrieve metadata value if it exists
		$tutsplus_expiry_date = get_post_meta( $post->ID, 'expires', true );
		?>
		
		<label for "tutsplus_expiry_date"><?php __('Expiry Date', 'tutsplus' ); ?></label>
				
		<input type="text" class="MyDate" name="tutsplus_expiry_date" value=<?php echo esc_attr( $tutsplus_expiry_date ); ?> / >
		
		<script type="text/javascript">
			jQuery(document).ready(function() {
				jQuery('.MyDate').datepicker({
					dateFormat : 'dd-mm-yy'
				});
			});
		</script>			
	
	</form>
	
<?php }
Copy after login

现在让我们看看保存插件文件后元框的样子:

Add expiration date to WordPress posts

那好多了!但是,尽管您现在可以为帖子添加到期日期,但这对于它们是否显示在您的网站上没有任何影响。现在让我们改变这一点。

修改查询以排除过期帖子

最后一步是使用 pre_get_posts 挂钩修改主查询。

仍在您的插件文件中工作,添加以下代码:

function tutsplus_filter_expired_posts( $query ) {
    
    // doesn't affect admin screens
    if ( is_admin() )
        return;
    // check for main query	
	if ( $query->is_main_query() ) {

    	//filter out expired posts
        $today = date('d-m-Y');
        $metaquery = array(
            array(
                 'key' => 'expires',
                 'value' => $today,
                 'compare' => '<',
                 'type' => 'DATE',
			)
        );
        $query->set( 'meta_query', $metaquery );
	}
}
add_action( 'pre_get_posts', 'tutsplus_filter_expired_posts' );
Copy after login

这做了六件事:

  • 首先,它定义 tutsplus_filter_expired_posts() 函数,并以 $query 作为其对象。
  • 它会检查我们是否位于管理屏幕中,因为我们不想排除其中过期的帖子。
  • 接下来,它检查主查询是否正在运行。
  • 如果是这样,它将变量 $today 定义为今天的日期,并使用与日期选择器相同的日期格式。
  • 然后,它使用 compare 运算符定义 $metaquery 来排除过期日期早于今天的帖子。
  • 最后,它使用 $metaquery 变量重置查询。

该函数与 pre_get_posts 挂钩,这将使其在查询获取帖子时运行。

现在保存您的插件文件并尝试一下。创建一个发布日期为几天前的帖子,然后为其指定昨天的到期日期。保存并切换到您的博客主页。您会发现您刚刚创建的帖子不在那里!

摘要

能够让您的帖子在给定日期自动过期非常有用。如果帖子的内容不再相关,或者您不希望人们在给定日期之后看到它,则添加到期日期可以让您不必记住在不再需要该帖子时编辑或删除该帖子。

通过使用 jQuery 日期选择器,您创建了一个用户友好的元框,您可以使用它来节省时间并避免访问者的困惑。

The above is the detailed content of Add expiration date to WordPress posts. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

How to change the head image of the wordpress theme How to change the head image of the wordpress theme Apr 20, 2025 am 10:00 AM

A step-by-step guide to replacing a header image of WordPress: Log in to the WordPress dashboard and navigate to Appearance &gt;Theme. Select the topic you want to edit and click Customize. Open the Theme Options panel and look for the Site Header or Header Image options. Click the Select Image button and upload a new head image. Crop the image and click Save and Crop. Click the Save and Publish button to update the changes.

What are the plugins for wordpress blocking ip What are the plugins for wordpress blocking ip Apr 20, 2025 am 08:27 AM

WordPress IP blocking plugin selection is crucial. The following types can be considered: based on .htaccess: efficient, but complex operation; database operation: flexible, but low efficiency; firewall: high security performance, but complex configuration; self-written: highest control, but requires more technical level.

How to import the source code of wordpress How to import the source code of wordpress Apr 20, 2025 am 11:24 AM

Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.

How to view the front-end of WordPress How to view the front-end of WordPress Apr 20, 2025 am 10:30 AM

You can view the WordPress front-end by logging into the dashboard and switching to the View Sites tab; automate the viewing process with a headless browser; installing the WordPress plugin to preview the front-end within the dashboard; viewing the front-end via a local URL (if WordPress is set locally).

How to cancel the editing date of wordpress How to cancel the editing date of wordpress Apr 20, 2025 am 10:54 AM

WordPress editing dates can be canceled in three ways: 1. Install the Enable Post Date Disable plug-in; 2. Add code in the functions.php file; 3. Manually edit the post_modified column in the wp_posts table.

How to write a header of a wordpress How to write a header of a wordpress Apr 20, 2025 pm 12:09 PM

The steps to create a custom header in WordPress are as follows: Edit the theme file "header.php". Add your website name and description. Create a navigation menu. Add a search bar. Save changes and view your custom header.

See all articles