我试图创建在将更改状态从“草稿”更改为“发布”时运行的wordpress代码段。发布更改状态后,我的代码段发现标题为a的单词替换为同义词。我发现了wordpress动作“ draft_to_publish”。但是我不知道如何将wordpress标题保存为字符串,以及如何使用新标题和新标题保存帖子。
这是个主意
[https://pastebin.com/CBYAZRfr]
有什么想法吗? :(
答案 0 :(得分:0)
像这样你可以做到
function action_post_draft_to_publish($post){
if( $post->post_type == 'post' ) : //Check Post Type, You may update it accordingly for your need
$title = $post->post_title;
// Convert title to lowercase
$lowTitle = mb_convert_case($title, MB_CASE_LOWER, "UTF-8");
// Synonymous for replace
$synonymous = array(
'beautiful' => 'perect',
'vehicle' => 'car',
);
// Loop with word check and replace
foreach($synonymous as $key => $value) {
if( is_string($key) ) {
$stringKey = $key;
// Replace in title
if (strpos($lowTitle, $stringKey) !== false) {
$lowTitle = str_replace($stringKey, $value, $lowTitle);
}
}
}
wp_update_post( array(
'ID' => $post->ID,
'post_title' => $lowTitle //Use Your Updated Title Which You Want to Use
) );
endif; //Endif
}
add_action('draft_to_publish', 'action_post_draft_to_publish', 20);
答案 1 :(得分:0)
您能否在此挂钩中检查代码
// define the draft_to_publish callback
function action_draft_to_publish( $array ) {
// make action magic happen here...
};
// add the action
add_action( 'draft_to_publish', 'action_draft_to_publish', 10, 1 );
答案 2 :(得分:0)
您可以使用以下代码段:
function draft_to_publish( $post ) {
$title = $post['post_title'];
$lowTitle = mb_convert_case($title, MB_CASE_LOWER, "UTF-8");
// Synonymous for replace
$synonymous = array(
'beautiful' => 'perect',
'vehicle' => 'car',
);
// Loop with word check and replace
foreach ($synonymous as $key => $value) {
if(is_string($key)) {
$stringKey = $key;
// Replace in title
if (strpos($lowTitle, $stringKey) !== false) {
$lowTitle = str_replace($stringKey, $value, $lowTitle);
}
}
}
// Update post
$my_post = array(
'ID' => $post['ID'],
'post_title' => $lowTitle, // new title
);
// Update the post into the database
wp_update_post( $my_post );
}
add_action( 'draft_to_publish', 'draft_to_publish' );