在帖子标题的末尾动态添加唯一的编号/标识符

时间:2019-03-05 作者:Razey

我目前正在开发一个小型招聘网站,遇到了一个问题。

我创建了一个表单(使用重力表单),允许用户创建自定义帖子(当前空缺),并有一个隐藏字段,可以从其他字段中动态提取帖子标题。

然而,由于将有许多帖子标题几乎相同,我想动态添加一种方法来识别它们,例如NTS0001等。为每个创建的新帖子添加一个额外的数字。

我使用多种帖子类型来帮助组织我网站的每个部分,我只想将此动态编号/标识符添加到一个单一的自定义帖子类型(称为“current\\u空缺”

P、 如果可能的话,我也希望这篇文章的URL中也能显示出来。我知道Wordpress有数字永久链接设置,但是它总是和帖子标题一样吗?

希望这是有意义的。

2 个回复
SO网友:Jay Pagnis

您需要利用post_updated Wordpress的钩子API

// You will need to leverage the <code>save post</code> hook API of Wordpress
add_action( \'post_updated\', \'save_post_callback\', 10, 3 );

//add_action(\'save_post\', \'save_post_callback\');
function save_post_callback($post_ID, $post_after, $post_before){
    global $post;
    if ($post->post_type != \'page\'){
        return;
    }

    // If you get here then it\'s your post type so do your thing....
    // unhook this function so it doesn\'t loop infinitely
    remove_action(\'post_updated\', \'save_post_callback\');

    $title = $post_after->post_title;
    // Check if "NTS00" is already there,
    // Deliberately checking if position found is > 0
    if( strpos($title, "NTS00") == FALSE ){
        // Set the title
        $args = array(
            \'ID\'           => $post_ID,
            \'post_title\'   => $title.\'_NTS000\'.$post_ID
        );
        // update the post, which calls save_post again
        wp_update_post( $args );
        // Bonus! 
        update_post_meta( $post_ID, \'my_key\', \'NTS000\'.$post_ID );
        // re-hook this function
        add_action(\'post_updated\', \'save_post_callback\');

    }
}
这样,您将确保NTS00 只追加一次。奖金功能将确保您还为"custom key" 作为post meta。

我希望我能帮忙。

SO网友:Dave from Gravity Wiz

你可以用这样的东西Gravity Forms Unique ID 在提交表单时生成唯一的顺序ID。

然后,您可以在帖子标题字段的content template 将其作为生成的帖子标题的一部分。

相关推荐