Home >Web Front-end >HTML Tutorial >Add expiration date to WordPress posts
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:
pre_get_posts
hook to ensure that posts with an expired date are not displayed. To complete this tutorial you will need:
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!
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 */
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.
First we will create the meta box for the expiration date.
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' );
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.
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 }
Let’s see what it does:
tutsplus_expiry_date_metabox_callback()
callback function, with $post
as its object. $tutsplus_expiry_date
with the value of the 'expires'
meta key as its value. 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
. 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.
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' );
This does the following:
edit_post
能力。isset
检查数据是否已添加到元框字段。$new_expiry_date
的变量,并将其定义为输入的值。所以我们现在有一个元框,它可以让用户添加文本并将其保存到帖子元数据中。让我们让它更安全。
为了确保帖子元数据仅通过此表单进行编辑,我们将添加一个随机数。
在回调函数中,在函数的其余内容之前,添加以下代码:
wp_nonce_field( 'tutsplus_expiry_date_metabox_nonce', 'tutsplus_nonce' );
接下来,在用于保存数据的 tutsplus_save_expiry_date_meta()
函数中,在函数开头添加以下内容:
if( !isset( $_POST['tutsplus_nonce'] ) || !wp_verify_nonce( $_POST['tutsplus_nonce'], 'tutsplus_expiry_date_metabox_nonce' ) ) return;
现在保存您的插件并查看您的帖子编辑屏幕。您将看到您的元框:
这是一个好的开始,但问题是目前这是一个普通的文本字段,所以没有办法确保您的用户仅以正确的格式输入日期。我们将通过添加 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' );
这会将脚本本身和存储在 Google API 上的脚本样式表排入队列。请注意,您必须将其挂钩到 admin_enqueue_scripts
操作挂钩,而不是像在前端使用脚本时那样挂钩到 wp_enqueue_scripts
。
接下来,您需要将脚本添加到输出表单的回调函数中。在 input 元素之后和结束 标记之前,添加以下内容:
<script type="text/javascript"> jQuery(document).ready(function() { jQuery('.MyDate').datepicker({ dateFormat : 'dd-mm-yy' }); }); </script>
这引用了您已添加到输入元素的 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 }
现在让我们看看保存插件文件后元框的样子:
那好多了!但是,尽管您现在可以为帖子添加到期日期,但这对于它们是否显示在您的网站上没有任何影响。现在让我们改变这一点。
最后一步是使用 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' );
这做了六件事:
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!