我有一个令我疯狂和沮丧的代码,我想知道对像我这样的新手是否有什么帮助。以前也有类似的解决方案,但还不够。
我想能够自动生成带有作者名字、姓氏、随机数和当前日期的自定义帖子标题。问题是,只有当我按publish时,它才起作用。但当我保存为草稿而不最终发布时,情况就不一样了。我希望能够在草稿上生成,并且在发布时仍将保留生成的标题,而不是每次更新。
我的代码在这里:
function set_interview_title( $value, $post_id ) {
$label = \'INTERVIEW\';
$date = date("Ymd");
$date = date("Ymd", strtotime($date));
$uniqueid_length = 8;
$uniqueid = crypt(uniqid(rand(),1));
$uniqueid = strip_tags(stripslashes($uniqueid));
$uniqueid = str_replace(".","",$uniqueid);
$uniqueid = strrev(str_replace("/","",$uniqueid));
$uniqueid = substr($uniqueid,0,$uniqueid_length);
$uniqueid = strtoupper($uniqueid);
if($value[\'post_type\'] == \'interviews\') {
if( ( \'publish\' == $_POST[\'post_status\'] ) && ( \'publish\' == $_POST[\'original_post_status\'] ) ) {
return;
}
if( ( \'publish\' == $_POST[\'post_status\'] ) && ( \'publish\' != $_POST[\'original_post_status\'] ) ) {
$title = $label . \' - \' . $uniqueid . \'-\' . $date;
$post_slug = sanitize_title_with_dashes ($title,\'\',\'save\');
$post_slugsan = sanitize_title($post_slug);
$value[\'post_title\'] = $title;
$value[\'post_name\'] = $post_slugsan;
}
if( ( \'draft\' == $_POST[\'post_status\'] ) || ( \'pending\' == $_POST[\'post_status\'] ) ) {
$title = $label . \' - \' . $uniqueid . \'-\' . $date;
$post_slug = sanitize_title_with_dashes ($title,\'\',\'save\');
$post_slugsan = sanitize_title($post_slug);
$value[\'post_title\'] = $title;
$value[\'post_name\'] = $post_slugsan;
}
} return $value;
}
add_filter( \'wp_insert_post_data\' , \'set_interview_title\' , \'10\', 2 );
谢谢
最合适的回答,由SO网友:Mike 整理而成
像这样的东西应该可以使用JS在新帖子的初始加载时设置标题。您不需要区分发布/草稿等,您可以让WordPress进行清理。
function set_post_title( $post ) {
global $current_user;
if( get_post_type() != \'interviews\' || $post->post_status != \'auto-draft\' )
return;
$uniqueid_length = 8;
$uniqueid = crypt(uniqid(rand(),1));
$uniqueid = strip_tags(stripslashes($uniqueid));
$uniqueid = str_replace(".","",$uniqueid);
$uniqueid = strrev(str_replace("/","",$uniqueid));
$uniqueid = substr($uniqueid,0,$uniqueid_length);
$uniqueid = strtoupper($uniqueid);
$title = \'INTERVIEW: \' . $current_user->first_name . \' \' . $current_user->last_name . \' - \' . $uniqueid . \' - \' . date( \'Ymd\' );
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#title").val("<?php echo $title; ?>");
$("#title").prop("readonly", true); // Don\'t allow author/editor to adjust the title
});
</script>
<?php
} // set_post_title
add_action( \'edit_form_after_title\', \'set_post_title\' ); // Set the post title for Custom posts