disallow publish posts with special title

admin2025-06-03  3

I want to disallow some titles on wordpress and avoid publishing these posts.

example : "title : last news 8 hours ago"

When this sentence is in the post title, I want disallow publish the post. What's the solution?

I want to disallow some titles on wordpress and avoid publishing these posts.

example : "title : last news 8 hours ago"

When this sentence is in the post title, I want disallow publish the post. What's the solution?

Share Improve this question edited Feb 12, 2019 at 23:12 rudtek 6,4035 gold badges30 silver badges52 bronze badges asked Feb 12, 2019 at 22:54 mgt1234mgt1234 1 1
  • Can you provide some context? What problem is this solving for you? – Tom J Nowell Commented Feb 12, 2019 at 23:49
Add a comment  | 

1 Answer 1

Reset to default 2

The "easy" answer is: put a filter on it.

add_action( 'transition_post_status', 'my_function', 10, 3 );

function my_function( $new_status, $old_status, $post )
{
    if ( 'publish' !== $new_status or 'publish' === $old_status )
        return;

    if ( 'post' !== $post->post_type )
        return; // restrict the filter to a specific post type

    $title = $post->post_title;

  $restricted_title = "title : last news 8 hours ago";

  if ($title == $restricted_title){ //if title matches unpublish
     wp_update_post(array(
        'ID'    =>  $post->ID,
        'post_status'   =>  'draft'
        ));
  }
}

But if the title is slightly different from the string you hardcode it will fail. My suggestion is to make a list of "restricted words" or phrases and check all of them. Like this:

add_action( 'transition_post_status', 'my_function', 10, 3 );

function my_function($new_status, $old_status, $post){

   if ( 'publish' !== $new_status or 'publish' === $old_status )
        return;

  if ( 'post' !== $post->post_type )
        return; // restrict the filter to a specific post type

  $title = $post->post_title;

  // Add restricted words or phrases separated by a semicolon

  $restricted_words = "word1;word2;word3";

  $restricted_words = explode(";", $restricted_words);
  foreach($restricted_words as $restricted_word){
    if (stristr( $title, $restricted_title)){ //if title matches unpublish
     wp_update_post(array(
        'ID'    =>  $post->ID,
        'post_status'   =>  'draft'
        ));
    }
  }
}

Anyway, my take on this is that you will never be 100% sure that these kind of filter works. You should really do it by hand.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748912769a314758.html

最新回复(0)