繁体   English   中英

save_post function 未被调用

[英]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);

我不知道我错过了什么

function is_single在此挂钩中不起作用(即使将帖子 ID 作为参数)。 根据文档,挂钩publish_post已经指定它是一篇文章,请参见此处,因此 if 语句不是必需的。 后缀_post定义挂钩有效的帖子类型。

我也会将帖子作为参数传递。

function catch_that_image($post_id, $post)
{
    ...
}

add_action('publish_post', 'catch_that_image', 10, 2);

作为替代方案,我建议使用transition_post_status挂钩,请参见此处

我会推荐你挂钩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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM