我开发了一个功能,可以检查更新帖子上是否存在特定帖子元值的重复值。当用户更新数据时,如果发现任何记录,则在管理仪表板中给出错误消息(请参阅随附的屏幕截图)。您可以根据需要使用以下代码。
class Check_duplicate_entry {
public function __construct(){
add_action( \'save_post\', array( $this, \'save_post\' ) );
add_action( \'admin_notices\', array( $this, \'admin_notices_callback\' ) );
}
public function save_post( $post_id ) {
global $wpdb;
$issue_id = $_POST[\'issue_magazine_id\'];
$issue_number = $_POST[\'issue_number\'];
$query = "SELECT $wpdb->posts.ID FROM $wpdb->posts INNER JOIN wp_postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id ) INNER JOIN $wpdb->postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND (
( $wpdb->postmeta.meta_key = \'issue_magazine_id\' AND $wpdb->postmeta.meta_value = $issue_id )
AND
( mt1.meta_key = \'issue_number\' AND mt1.meta_value = $issue_number )
)";
$result = $wpdb->get_results($query);
if($result && $post_id != $result[0]->ID){
// Add your query var if the coordinates are not retreive correctly.
add_filter( \'redirect_post_location\', array( $this, \'add_notice_query_variable\' ), 99 );
}
else
{
if ( !empty( $_POST[ \'issue_magazine_id\' ] ) ) {
update_post_meta( $post_id, \'issue_magazine_id\', $_POST[ \'issue_magazine_id\' ]);
} else {
delete_post_meta( $post_id, \'issue_magazine_id\' );
}
if ( !empty( $_POST[ \'issue_number\' ] ) ) {
update_post_meta( $post_id, \'issue_number\', $_POST[ \'issue_number\' ]);
} else {
delete_post_meta( $post_id, \'issue_number\' );
}
}
}
public function add_notice_query_variable( $location ) {
remove_filter( \'redirect_post_location\', array( $this, \'add_notice_query_variable\' ), 99 );
return add_query_arg( array( \'issue_magazine_id\' => $_POST[\'issue_magazine_id\'],\'issue_number\' => $_POST[\'issue_number\'] ), $location );
}
public function admin_notices_callback() {
if ( ! isset( $_GET[\'issue_magazine_id\'] ) && ! isset( $_GET[\'issue_number\'] ) ) {
return;
}
?>
<div class="error notice">
<p><?php esc_html_e( \'Issue ID : \'.$_GET[\'issue_magazine_id\'].\' and Issue Number : \'. $_GET[\'issue_number\'].\' already updated in other post, Please try different!\', \'\' ); ?></p>
</div>
<?php
}
}
$Check_duplicate_entry = new Check_duplicate_entry();
也许这对你有帮助。如果这对你有帮助,请告诉我!
非常感谢。