我正在使用此功能根据几个自定义字段自动设置帖子标题:
function set_event_title( $data , $postarr ) {
if($data[\'post_type\'] == \'event\') {
$getdate = get_post_meta($postarr[\'ID\'],\'event_datestart\',true);
$dateformat = new DateTime($getdate);
$date = $dateformat->format( \'m-d-Y\' );
$event_venue = get_post_meta($postarr[\'ID\'],\'venue_name\',true);
$event_title = $event_venue . \' - \' . $date;
$post_slug = sanitize_title_with_dashes ($event_title,\'\',\'save\');
$post_slugsan = sanitize_title($post_slug);
$data[\'post_title\'] = $event_title;
$data[\'post_name\'] = $post_slugsan;
}
return $data;
}
add_filter( \'wp_insert_post_data\' , \'set_event_title\' , \'99\', 2 );
但我只能在帖子更新时使用它,而不能在帖子的初始发布时使用它。有没有一种方法可以让这篇文章在保存后的第一次和其余时间都有效?
SO网友:Vinod Dalvi
不要从get\\u post\\u meta函数中获取meta值,而是从$postarr数组中获取meta值,因为在初始发布帖子时,数据库中没有event\\u datestart和venue\\u name的任何值,它返回空字符串。
Updated Code :
function set_event_title( $data , $postarr ) {
if($data[\'post_type\'] == \'event\') {
$getdate = $postarr[\'event_datestart\']; // Replace event_datestart with the input field name of event_datestart post meta.
$dateformat = new DateTime($getdate);
$date = $dateformat->format( \'m-d-Y\' );
$event_venue = $postarr[\'venue_name\']; // Replace venue_name with the input field name of venue_name post meta.
$event_title = $event_venue . \' - \' . $date;
$post_slug = sanitize_title_with_dashes ($event_title,\'\',\'save\');
$post_slugsan = sanitize_title($post_slug);
$data[\'post_title\'] = $event_title;
$data[\'post_name\'] = $post_slugsan;
}
return $data;
}
add_filter( \'wp_insert_post_data\' , \'set_event_title\' , \'99\', 2 );
有关更多信息,请参阅
this page.