[英]save_post function is not called
我正在尝试使用我的 function 调用 save_post 或 publish_post 挂钩,但无法触发 function。
我的 function 在 single.php 上运行良好,但它只在浏览帖子后分配缩略图。 所以我决定把它放在 functions.php 里面,但是我无法用 save_post 或 publish_post 钩子触发它。
这是代码
function catch_that_image($post_id) {
if(is_single()){
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "https://images.arabicpdfs.com/المكتبة-المفتوحة.jpg";
}
//return $first_img;
if ( has_post_thumbnail() ) {
return;
}
else{
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$url =$first_img;
$desc = "image description";
$post_id =$post->ID;
$image = media_sideload_image( $url, $post_id, $desc,'id' );
set_post_thumbnail( $post_id, $image );
//echo $post_id;
}
}}
add_action( 'publish_post', 'catch_that_image', 10, 1);
我不知道我错过了什么
我会推荐你挂钩transition_post_status
function custom_transition_post_status($new_status, $old_status, $post)
{
// here you can do your action something like this
if(is_single() && $post->post_type == 'post') {
...
}
}
add_action('transition_post_status', 'custom_transition_post_status', 10, 3);
插入或更新应使用 function wp_insert_post
。 如果您想更新您的帖子,请添加字段 ID。
$postData = [
'post_title' => 'your title',
'post_status' => 'publish',
'post_type' => 'post'
];
$postId = wp_insert_post($postData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.