从两个元字段设置帖子标题

时间:2013-04-03 作者:Eckstein

在自定义帖子类型中,我禁用了帖子标题,但是在帖子列表和slug中,它只是将标题显示为“自动草稿”。我想自动获取两个post meta,然后生成标题和slug。

我以为这会奏效,但我无法做到:

function set_event_title( $data , $postarr ) {
  if($data[\'post_type\'] == \'events\') {
    $event_date = get_post_meta($post_id,\'event_datetime\',true);
    $event_venue = get_post_meta($post_id, \'venue_name\' , true);
    $event_title = $event_venue . \' - \' . $event_date;
    $post_slug = sanitize_title_with_dashes ($event_title,\'\',\'save\');
    $post_slugsan = sanitize_title($post_slug);

    $data[\'post_title\'] = $post_title;
    $data[\'post_name\'] = $post_slugsan;
  }
  return $data;
}

add_filter( \'wp_insert_post_data\' , \'set_event_title\' , \'99\', 2 );
有人知道我怎样才能让它正确地工作吗?

2 个回复
最合适的回答,由SO网友:Vinod Dalvi 整理而成

您在以下行中使用了错误的变量:

$data[\'post_title\'] = $post_title;
您应该在$post\\U标题中使用$event\\U标题,如下所示:

$data[\'post_title\'] = $event_title;
还可以从$postarr参数获取Post ID。

Updated Code :

function set_event_title( $data , $postarr ) {
  if($data[\'post_type\'] == \'events\') {
    $event_date = get_post_meta($postarr[\'ID\'],\'event_datetime\',true);
    $event_venue = get_post_meta($postarr[\'ID\'], \'venue_name\' , true);
    $event_title = $event_venue . \' - \' . $event_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\' , \'10\', 2 );
有关此筛选器的详细信息,请访问this page.

SO网友:Jesse Pearson

我发现前面的答案,如评论中所述,只在保存现有帖子时有效,而不在保存新帖子时有效。以下内容适用于新员额和现有员额。

// func that is going to set our title of our customer magically
function w2w_customers_set_title( $data , $postarr ) {

    // We only care if it\'s our customer
    if( $data[ \'post_type\' ] === \'w2w-customers\' ) {

        // get the customer name from _POST or from post_meta
        $customer_name = ( ! empty( $_POST[ \'customer_name\' ] ) ) ? $_POST[ \'customer_name\' ] : get_post_meta( $postarr[ \'ID\' ], \'customer_name\', true );

        // if the name is not empty, we want to set the title
        if( $customer_name !== \'\' ) {

            // sanitize name for title
            $data[ \'post_title\' ] = $customer_name;
            // sanitize the name for the slug
            $data[ \'post_name\' ]  = sanitize_title( sanitize_title_with_dashes( $customer_name, \'\', \'save\' ) );
        }
    }
    return $data;
}
add_filter( \'wp_insert_post_data\' , \'w2w_customers_set_title\' , \'99\', 2 );
它首先检查$_POST 变量,这是它在大多数情况下的来源。如果它不在那里,它将从post_meta, 它可以处理快速编辑之类的事情。

结束

相关推荐

用可调整大小的图像替换#SITE-TITLE吗?

整个下午我都在绞尽脑汁。我成功地使用CSS将#站点标题替换为图像,在桌面上浏览时看起来很好,但我希望整个站点都能响应(毕竟我使用的是212!)。问题是,为了在CSS中替换#站点标题,您必须应用固定的维度。使用“100%”、“auto”等只会将图像从页面上完全擦除。我还尝试添加“宽度:100%;”到#页,它是父级,没有用。有什么想法吗?。