不允许发布带有特殊标题的帖子

时间:2019-02-12 作者:mgt1234

我想禁止wordpress上的一些标题,并避免发布这些帖子。

示例:"title : last news 8 hours ago"

当这句话出现在帖子标题中时,我想禁止发布帖子。解决方案是什么?

1 个回复
SO网友:Fabrizio Mele

“简单”的答案是:在上面加一个过滤器。

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\'
        ));
  }
}
但是,如果标题与硬编码的字符串略有不同,它将失败。我的建议是列一个“限制词”或短语的列表,并检查所有这些词或短语。像这样:

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\'
        ));
    }
  }
}
无论如何,我对这一点的看法是,你永远不会百分之百确定这种过滤器是否有效。你真的应该手工做。