Wordpress validation for title - wordpress

Need to add blank and already exist validation for 'supports' => array( 'title') on my custom post type. But i dont want to use any plugin for this.
Thanks in advance.
add_action( 'admin_notices', 'custom_error_notice' );
function custom_error_notice(){
global $current_screen, $post;
if ( $current_screen->parent_base == 'edit' ){
if((!$post->post_name) && $_GET['post']) {
wp_redirect(admin_url('post-new.php?empty=1'));
}
if($_GET['empty']) echo '<div class="error"><p>Warning - Please fill up all fields correctly!</p></div>';
}
}
But this not working properly.

This may help you:-
add_action('save_post', 'album_save_post', 10, 2);
function album_save_post( $album_id, $album ) {
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || $album->post_type != 'music_album') return;
// echo '<pre>';
// print_r($album);
// echo '</pre>';
// die();
$errors = array();
// Validation filters
$title = $album->post_title;
if ( ! $title ) {
$errors['title'] = "The title is required";
}
// if we have errors lets setup some messages
if (! empty($errors)) {
// we must remove this action or it will loop for ever
remove_action('save_post', 'album_save_post');
// save the errors as option
update_option('album_errors', $errors);
// Change post from published to draft
$album->post_status = 'draft';
// update the post
wp_update_post( $album );
// we must add back this action
add_action('save_post', 'album_save_post');
// admin_notice is create by a $_GET['message'] with a number that wordpress uses to
// display the admin message so we will add a filter for replacing default admin message with a redirect
add_filter( 'redirect_post_location', 'album_post_redirect_filter' );
}
}
function album_post_redirect_filter( $location ) {
// remove $_GET['message']
$location = remove_query_arg( 'message', $location );
// add our new query sting
$location = add_query_arg( 'album', 'error', $location );
// return the location query string
return $location;
}
// Add new admin message
add_action( 'admin_notices', 'album_post_error_admin_message' );
function album_post_error_admin_message() {
if ( isset( $_GET['album'] ) && $_GET['album'] == 'error' ) {
// lets get the errors from the option album_errors
$errors = get_option('album_errors');
// now delete the option album errors
delete_option('album_errors');
$display = '<div id="notice" class="error"><ul>';
// Because we are storing as an array we should loop through them
foreach ( $errors as $error ) {
$display .= '<li>' . $error . '</li>';
}
$display .= '</ul></div>';
// finally echo out our display
echo $display;
// add some jQuery
?>
<script>
jQuery(function($) {
$("#title").css({"border": "1px solid red"})
});
</script>
<?php
}
}

i got the solution.
/** ADD Validation for title */
function force_post_title_init()
{
wp_enqueue_script('jquery');
}
function force_post_title()
{
echo "<script type='text/javascript'>\n";
echo "
jQuery('#publish').click(function(){
var testervar = jQuery('[id^=\"titlediv\"]')
.find('#title');
if (testervar.val().length < 1)
{
jQuery('[id^=\"titlediv\"]').css('border', '1px solid red');
alert('Post title is required');
return false;
}
});
";
echo "</script>\n";
}
add_action('admin_init', 'force_post_title_init');
add_action('edit_form_advanced', 'force_post_title');
// Add this row below to get the same functionality for page creations.
add_action('edit_page_form', 'force_post_title');
May be this also help for all of you.

Related

Wordpress save_post creates duplicate content in 1 entry

I am encountering issue whereby my post content got duplicated. I want to be able to modify the content only on first publish. I tried to use wp_insert_post_data filter but it keeps crashing. So i use save_post. Here is what I want to achieve.
Example:
This is my post and I [bbsmall]create it using[/bbsmall] save_post
Filter:
Remove tag and use only simple html tags and do many other modification.
Ideal Output:
This is my post and I create it using save_post
However, my current output is:
This is my post and I create it using save_post
This is my post and I create it using save_post
This is my code
add_action('save_post', 'my_modified_content');
function my_modified_content($post_id) {
$post_content = get_post( $post_id );
if( $post_content->post_type != "post" ) {
return;
}else{
if (isset($post_content->post_status) && 'auto-draft' == $post_content->post_status ) {
return;
}
else{
$add_extra_tag = $myweb_settings['myoption_set'];
$post_checked = get_post_meta( $post_id, 'my_post_meta_style', true );
$alreadydone = get_post_meta( $post_id, 'check_post_style', true );
if ($alreadydone!=1){
if (isset($add_extra_tag) and $add_extra_tag=="Yes"){
remove_action('save_post', 'my_modified_content');
$content = add_simple_tags($post_content->post_content);
$title =add_simple_tags($post_content->post_title);
update_post_meta($post_id, 'check_post_style', '1');
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $title;
$my_post['post_content'] = $content;
$my_post['post_status'] = 'publish';
wp_update_post($my_post);
add_action('save_post', 'my_modified_content');
}else{
if (isset($post_checked ) ) {
remove_action('save_post', 'my_modified_content');
$content = add_simple_tags($post_content->post_content);
$title =add_simple_tags($post_content->post_title);
update_post_meta($post_id, 'check_post_style', '1');
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $title;
$my_post['post_content'] = $content;
$my_post['post_status'] = 'publish';
wp_update_post($my_post);
add_action('save_post', 'my_modified_content');
}else{
return ;
}
}
}else{
return ;
}
}
}
}
Okay so I am able to fix the issue.
Instead of using save_post, I use wp_insert_post_data filter.
Previously I failed to use the filter due to the wrong format of coding and I did not return the $data.
So these are the modifications I did. Hope this is helpful for others who are facing the same issue.
add_filter('wp_insert_post_data', 'my_modified_content',10,3);
function my_modified_content($data, $postarr, $unsanitized_postarr) {
if( $data['post_type'] != "post" ) {
return;
}else{
if (isset($data['post_status']) && 'auto-draft' == $data['post_status'] ) {
return;
}
else{
$add_extra_tag = $myweb_settings['myoption_set'];
$post_checked = $postarr['my_post_meta_style'];
//Do other checks and modifications
}
}
return $data;
}

how convert simple form submit to ajax submit without loading page like add product to cart function

how convert simple form submit to ajax submit without loading page like add the product to cart function
`
">
">
<button type="submit" name="addift_add_wl_btn_popup">Add to Wishlist</button>
</form>
session
public function addify_get_sectiuon_btn() {
$wl_p_id = '';
if ( isset( $_POST['addift_add_wl_btn_popup'] ) ) {
if ( isset( $_POST['addify_wl_product_id'] ) ) {
$addify_add_to_wl_pro = sanitize_text_field( wp_unslash( $_POST ['addify_wl_product_id'] ) );
}
$addify_wl_var1 = array();
$addify_wl_var1 = WC()->session->get( 'addify_section_name' );
if ( !empty( $addify_wl_var1) ) {
$addify_wl_var2 =$addify_add_to_wl_pro;
array_push( $addify_wl_var1 ,$addify_wl_var2);
WC()->session->set( 'addify_section_name', $addify_wl_var1 );
} else {
WC()->session->set( 'addify_section_name', array($addify_add_to_wl_pro) );
}
// WC()->session->set( 'addify_section_name', null );
}
}
#In jQuery#
listen to form submit and attach this code.
Remember to add event.preventDefault()'
$.post(
ajaxurl,
{ action: 'action_registered_by_add_action', addift_add_wl_btn_popup: addift_add_wl_btn_popup, addify_wl_product_id:addify_wl_product_id },
function( response ) {
//do something
}
);
#In PHP#
//register ajax
add_action( 'wp_ajax_ACTION_NAME', function(){
//base stufs here
} );
```--
###or###
add_action( 'wp_ajax_ACTION_NAME', [$this, 'method'] );
##EDITED##
//add this register to handle both logged in and not logged in users
//add_action( 'wp_ajax_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
//add_action( 'wp_ajax_nopriv_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
( function ( $ ) {
$( function () {
$( document ).ready( function ( $ ) {
jQuery( '.addift_add_wl_btn_popup_class' ).click( function () {
alert( "ok" );
} );
$( '.addift_add_wl_btn_popup_class' ).click( function ( event ) {
event.preventDefault(); //prevent default behaviour - you have must add function param named `event`
/*
* if its *.js file you must localize script to add variable see more https://wordpress.stackexchange.com/a/190299
* if its *.php file you can do this dirty inline php inside script
*/
let ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ) ?>"; // wp ajax url obtain by wc helper {{ admin_url( 'admin-ajax.php' ) }}
let addift_add_wl_btn_popup = $('#addift_add_wl_btn_popup').val(); // or anything else - value taken from form
let addify_wl_product_id = $('#addify_wl_product_id').val(); // or anything else - value taken from form
$.post( ajaxurl, {
action: 'addify_get_sectiuon_btn',
addift_add_wl_btn_popup: addift_add_wl_btn_popup,
addify_wl_product_id: addify_wl_product_id
},
function ( response ) {
//do something s
} );
} );
} );
} );
} )( jQuery );
my jquery
hook
add_action( 'wp_ajax_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
hook call back is
public function addify_get_sectiuon_btn() {
$wl_p_id = '';
if ( isset( $_POST['addift_add_wl_btn_popup'] ) ) {
if ( isset( $_POST['addify_wl_product_id'] ) ) {
$addify_add_to_wl_pro = sanitize_text_field( wp_unslash( $_POST ['addify_wl_product_id'] ) );
}
$addify_wl_var1 = array();
$addify_wl_var1 = WC()->session->get( 'addify_section_name' );
if ( !empty( $addify_wl_var1) ) {
$addify_wl_var2 =$addify_add_to_wl_pro;
array_push( $addify_wl_var1 ,$addify_wl_var2);
WC()->session->set( 'addify_section_name', $addify_wl_var1 );
} else {
WC()->session->set( 'addify_section_name', array($addify_add_to_wl_pro) );
}
// WC()->session->set( 'addify_section_name', null );
}
}

how to remove custom post type from wordpress url?

I have a wordpress website which is using the custom template with custom post types like landing and services.
Each post type have a specific slug in the url like this => (http://example.com/landing/landing-page-name)
I want to change this url (http://example.com/landing/landing-page-name) to this url (http://example.com/landing-page-name).
In fact I need to remove the [landing] phrase from the url. The important thing is that the [landing] is a custom post type in my posts table.
I have tested following solutions:
==> I have changed slug to '/' in rewrite property in register_post_type() --> It breaks the all of landings, posts and pages url (404)
==> I added 'with_front' => false to the rewrite property --> nothing changed
==> I tried to do this with RewriteRule in htaccess --> it did not work or give too many redirects error
I could not get a proper result.
Did anyone solve this problem before?
First, you need to filter the permalink for your custom post type so that all published posts don't have the slug in their URLs:
function stackoverflow_remove_cpt_slug( $post_link, $post ) {
if ( 'landing' === $post->post_type && 'publish' === $post->post_status ) {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'stackoverflow_remove_cpt_slug', 10, 2 );
At this point, trying to view the link would result in a 404 (Page Not Found) error. That's because WordPress only knows that Posts and Pages can have URLs like domain.com/post-name/ or domain.com/page-name/. We need to teach it that our custom post type's posts can also have URLs like domain.com/cpt-post-name/.
function stackoverflow_add_cpt_post_names_to_main_query( $query ) {
// Return if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Return if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Return if we're not querying based on the post name.
if ( empty( $query->query['name'] ) ) {
return;
}
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', array( 'post', 'page', 'landing' ) );
}
add_action( 'pre_get_posts', 'stackoverflow_add_cpt_post_names_to_main_query' );
try this code , 100% working single custom post type and multiple post type.
add this class in functions.php file in our theme , or create separate file and import into functions.php
class remove_cpt_base {
var $plugin_admin_page;
static $instance = null;
static public function init() {
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
}
function __construct() {
add_action('plugins_loaded', array($this, 'plugins_loaded'));
$this->rcptb_selected = get_option('rcptb_selected', array());
$this->rcptb_selected_keys = array_keys($this->rcptb_selected);
add_action('admin_menu', array($this, 'plugin_menu_link'));
add_filter('post_type_link', array($this, 'remove_slug'), 10, 3);
add_action('template_redirect', array($this, 'auto_redirect_old'), 1);
add_action('pre_get_posts', array($this, 'handle_cpts'), 1);
}
function plugins_loaded() {
load_plugin_textdomain('remove_cpt_base', FALSE, basename(dirname(__FILE__)) . '/languages/');
}
function filter_plugin_actions($links, $file) {
$settings_link = '' . __('Settings') . '';
array_unshift($links, $settings_link);
return $links;
}
function plugin_menu_link() {
$this->plugin_admin_page = add_submenu_page(
'options-general.php',
__('Remove CPT base', 'remove_cpt_base'),
__('Remove CPT base', 'remove_cpt_base'),
'manage_options',
basename(__FILE__),
array($this, 'admin_options_page')
);
add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'filter_plugin_actions'), 10, 2);
}
function admin_options_page() {
if (get_current_screen()->id != $this->plugin_admin_page) {
return;
}
global $wp_post_types;?>
<div class="wrap">
<h2><?php _e('Remove base slug from url for these custom post types:', 'remove_cpt_base')?></h2><?php
if (isset($_POST['rcptb_selected_sent'])) {
if (!isset($_POST['rcptb_alternation']) || !is_array($_POST['rcptb_alternation'])) {
$alternation = array();
} else {
$alternation = $_POST['rcptb_alternation'];
}
if (!isset($_POST['rcptb_selected']) || !is_array($_POST['rcptb_selected'])) {
$this->rcptb_selected = array();
} else {
$this->rcptb_selected = $_POST['rcptb_selected'];
}
foreach ($this->rcptb_selected as $post_type => $active) {
$this->rcptb_selected[$post_type] = isset($alternation[$post_type]) ? 1 : 0;
}
$this->rcptb_selected_keys = array_keys($this->rcptb_selected);
update_option('rcptb_selected', $this->rcptb_selected, 'no');
echo '<div class="below-h2 updated"><p>' . __('Settings saved.') . '</p></div>';
flush_rewrite_rules();
}?>
<br>
<form method="POST" action="">
<input type="hidden" name="rcptb_selected_sent" value="1">
<table class="widefat" style="width:auto">
<tbody><?php
foreach ($wp_post_types as $type => $custom_post) {
if ($custom_post->_builtin == false) {?>
<tr>
<td>
<label>
<input type="checkbox" name="rcptb_selected[<?php echo $custom_post->name ?>]" value="1" <?php echo isset($this->rcptb_selected[$custom_post->name]) ? 'checked' : '' ?>>
<?php echo $custom_post->label ?> (<?php echo $custom_post->name ?>)
</label>
</td>
<td>
<label>
<input type="checkbox" name="rcptb_alternation[<?php echo $custom_post->name ?>]" value="1" <?php echo isset($this->rcptb_selected[$custom_post->name]) && $this->rcptb_selected[$custom_post->name] == 1 ? 'checked' : '' ?>>
<?php _e('alternation', 'remove_cpt_base')?>
</label>
</td>
</tr><?php
}
}?>
</tbody>
</table>
<p><?php _e('* if your custom post type children return error 404, then try alternation mode', 'remove_cpt_base')?></p>
<hr>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save')?>">
</p>
</form>
</div><?php
}
function remove_slug($permalink, $post, $leavename) {
global $wp_post_types;
foreach ($wp_post_types as $type => $custom_post) {
if ($custom_post->_builtin == false && $type == $post->post_type && isset($this->rcptb_selected[$custom_post->name])) {
$custom_post->rewrite['slug'] = trim($custom_post->rewrite['slug'], '/');
$permalink = str_replace('/' . $custom_post->rewrite['slug'] . '/', '/', $permalink);
}
}
return $permalink;
}
function get_current_url() {
$REQUEST_URI = strtok($_SERVER['REQUEST_URI'], '?');
$real_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$real_url .= $_SERVER['SERVER_NAME'] . $REQUEST_URI;
return $real_url;
}
function handle_cpts($query) {
// make sure it's main query on frontend
if (!is_admin() && $query->is_main_query() && !$query->get('queried_object_id')) {
// conditions investigated after many tests
if ($query->is_404() || $query->get('pagename') || $query->get('attachment') || $query->get('name') || $query->get('category_name')) {
// test both site_url and home_url
$web_roots = array();
$web_roots[] = site_url();
if (site_url() != home_url()) {
$web_roots[] = home_url();
}
// polylang fix
if (function_exists('pll_home_url')) {
if (site_url() != pll_home_url()) {
$web_roots[] = pll_home_url();
}
}
foreach ($web_roots as $web_root) {
// get clean current URL path
$path = $this->get_current_url();
$path = str_replace($web_root, '', $path);
// fix missing slash
if (substr($path, 0, 1) != '/') {
$path = '/' . $path;
}
// test for posts
$post_data = get_page_by_path($path, OBJECT, 'post');
if (!($post_data instanceof WP_Post)) {
// test for pages
$post_data = get_page_by_path($path);
if (!is_object($post_data)) {
// test for selected CPTs
$post_data = get_page_by_path($path, OBJECT, $this->rcptb_selected_keys);
if (is_object($post_data)) {
// maybe name with ancestors is needed
$post_name = $post_data->post_name;
if ($this->rcptb_selected[$post_data->post_type] == 1) {
$ancestors = get_post_ancestors($post_data->ID);
foreach ($ancestors as $ancestor) {
$post_name = get_post_field('post_name', $ancestor) . '/' . $post_name;
}
}
// get CPT slug
$query_var = get_post_type_object($post_data->post_type)->query_var;
// alter query
$query->is_404 = 0;
$query->tax_query = NULL;
$query->is_attachment = 0;
$query->is_category = 0;
$query->is_archive = 0;
$query->is_tax = 0;
$query->is_page = 0;
$query->is_single = 1;
$query->is_singular = 1;
$query->set('error', NULL);
unset($query->query['error']);
$query->set('page', '');
$query->query['page'] = '';
$query->set('pagename', NULL);
unset($query->query['pagename']);
$query->set('attachment', NULL);
unset($query->query['attachment']);
$query->set('category_name', NULL);
unset($query->query['category_name']);
$query->set('post_type', $post_data->post_type);
$query->query['post_type'] = $post_data->post_type;
$query->set('name', $post_name);
$query->query['name'] = $post_name;
$query->set($query_var, $post_name);
$query->query[$query_var] = $post_name;
break;
} else {
// deeper matching
global $wp_rewrite;
// test all selected CPTs
foreach ($this->rcptb_selected_keys as $post_type) {
// get CPT slug and its length
$query_var = get_post_type_object($post_type)->query_var;
// test all rewrite rules
foreach ($wp_rewrite->rules as $pattern => $rewrite) {
// test only rules for this CPT
if (strpos($pattern, $query_var) !== false) {
if (strpos($pattern, '(' . $query_var . ')') === false) {
preg_match_all('#' . $pattern . '#', '/' . $query_var . $path, $matches, PREG_SET_ORDER);
} else {
preg_match_all('#' . $pattern . '#', $query_var . $path, $matches, PREG_SET_ORDER);
}
if (count($matches) !== 0 && isset($matches[0])) {
// build URL query array
$rewrite = str_replace('index.php?', '', $rewrite);
parse_str($rewrite, $url_query);
foreach ($url_query as $key => $value) {
$value = (int) str_replace(array('$matches[', ']'), '', $value);
if (isset($matches[0][$value])) {
$value = $matches[0][$value];
$url_query[$key] = $value;
}
}
// test new path for selected CPTs
if (isset($url_query[$query_var])) {
$post_data = get_page_by_path('/' . $url_query[$query_var], OBJECT, $this->rcptb_selected_keys);
if (is_object($post_data)) {
// alter query
$query->is_404 = 0;
$query->tax_query = NULL;
$query->is_attachment = 0;
$query->is_category = 0;
$query->is_archive = 0;
$query->is_tax = 0;
$query->is_page = 0;
$query->is_single = 1;
$query->is_singular = 1;
$query->set('error', NULL);
unset($query->query['error']);
$query->set('page', '');
$query->query['page'] = '';
$query->set('pagename', NULL);
unset($query->query['pagename']);
$query->set('attachment', NULL);
unset($query->query['attachment']);
$query->set('category_name', NULL);
unset($query->query['category_name']);
$query->set('post_type', $post_data->post_type);
$query->query['post_type'] = $post_data->post_type;
$query->set('name', $url_query[$query_var]);
$query->query['name'] = $url_query[$query_var];
// solve custom rewrites, pagination, etc.
foreach ($url_query as $key => $value) {
if ($key != 'post_type' && substr($value, 0, 8) != '$matches') {
$query->set($key, $value);
$query->query[$key] = $value;
}
}
break 3;
}
}
}
}
}
}
}
}
}
}
}
}
}
function auto_redirect_old() {
global $post;
if (!is_preview() && is_single() && is_object($post) && isset($this->rcptb_selected[$post->post_type])) {
$new_url = get_permalink();
$real_url = $this->get_current_url();
if (substr_count($new_url, '/') != substr_count($real_url, '/') && strstr($real_url, $new_url) == false) {
remove_filter('post_type_link', array($this, 'remove_slug'), 10);
$old_url = get_permalink();
add_filter('post_type_link', array($this, 'remove_slug'), 10, 3);
$fixed_url = str_replace($old_url, $new_url, $real_url);
wp_redirect($fixed_url, 301);
}
}
}
}
function rcptb_remove_plugin_options() {
delete_option('rcptb_selected');
}
add_action('init', array('remove_cpt_base', 'init'), 99);
register_activation_hook(__FILE__, 'flush_rewrite_rules');
register_deactivation_hook(__FILE__, 'flush_rewrite_rules');
register_uninstall_hook(__FILE__, 'rcptb_remove_plugin_options');
To the rewrite you just have to change your current slug from ‘cpt-slug’ to ‘/’ and the with-front: ‘false’. And done, you just resave permalinks and the url shouldn’t display the cpt slug anymore.
Having same issue and came across this answer and none of the above mentioned solution works so tried different plugins and the best which worked, removed base slug and solved 404 error try Remove CPT base

Making update notice functionality for my themes

I've created one of my themes.I want to add update functionality through api
The notice should be visible when I use the theme, if required for theme update
Actually i have no idea so please give me your suggestion or give me a code,so i can add functionality for update theme.
Note : If you have a no idea for api so you can provide another code
You can use site_transient_update_themes here:
add_filter ( 'site_transient_update_themes', 'theme_check_for_update' );
function theme_check_for_update ( $transient ) {
// Check Theme is active or not.
if( empty( $transient->checked['Your-Theme-Name'] ) )
return $transient;
$request = theme_fetch_data_of_latest_version();
if ( is_wp_error( $request ) || wp_remote_retrieve_response_code( $request ) != 200 ) {
return $transient;
} else {
$response = wp_remote_retrieve_body( $request );
}
$data = json_decode( $response );
if ( version_compare( $transient->checked['Your-Theme-Name'], $data->new_version, '<' ) ) {
$transient->response['Your-Theme-Name'] = (array) $data;
add_action('admin_notices', 'theme_update_admin_notice');
}
return $transient;
}
function theme_fetch_data_of_latest_version() {
// Your API call to check for new version
$request = wp_safe_remote_get( 'https://yourdomain.com/api/upgrade-json/' );
/*
Response Shoul be in following format:
{
"new_version": "1.0.4",
"url": "https://yourdomain.com/theme/changelog/",
"package": "https://yourdomain.com/theme/theme.zip"
}
*/
return $request;
}
function theme_update_admin_notice(){
echo '<div class="notice notice-warning notice-alt is-dismissible">
<p>New Theme Update is available.</p>
</div>';
}

Wordpress- Cancel post saving process

I need to abort the post saving process when the post content contains a specific string and then display a message to the user.
I found a method to display the message but didn't find a way to refuse post saving.
So far here's what i've done
add_action( "pre_post_update", "checkPost");
function checkPost($post_ID) {
$post = get_post($post_ID);
$postContent = $post->post_content;
if ( wp_is_post_revision( $post_ID ) )
return;
if(preg_match("/bad string/", $postContent) == 1) {
//
// cancel post save
//
// then
add_filter("redirect_post_location", "my_redirect_post_location_filter", 99);
}
}
function my_redirect_post_location_filter($location) {
remove_filter('redirect_post_location', __FUNCTION__, 99);
$location = add_query_arg('message', 99, $location);
return $location;
}
add_filter('post_updated_messages', 'my_post_updated_messages_filter');
function my_post_updated_messages_filter($messages) {
$messages['post'][99] = 'Publish not allowed';
return $messages;
}
Hope this helps you to check post content
function to_err_is_human( $post_id ) {
// If this is just a revision, don't check
if ( wp_is_post_revision( $post_id ) )
return;
$post_content = wp_unslash(!empty($_REQUEST['content']) ? $_REQUEST['content'] : $post_data['content']);
if ($post_content=="abc")
{ add_filter("redirect_post_location", "my_redirect_post_location_filter", 99);}
}
add_action( 'save_post', 'to_err_is_human' );
function my_redirect_post_location_filter($location) {
remove_filter('redirect_post_location', __FUNCTION__, 99);
$location = add_query_arg('message', 99, $location);
return $location;
}
add_filter('post_updated_messages', 'my_post_updated_messages_filter');
function my_post_updated_messages_filter($messages) {
$messages['post'][99] = 'Publish not allowed';
return $messages;
}

Resources