【问题标题】:How to avoid posts from moving to trash based off of a condition?如何避免帖子因条件而被移至垃圾箱?
【发布时间】:2021-06-01 16:07:41
【问题描述】:

问题:我应该如何进行有条件的“移至垃圾箱”操作?这意味着只有在满足特定条件时才删除特定帖子。否则,提示用户不能这样做。

我尝试过的事情:我正在pre_trash_hook 上调用一个函数并检查我的状况。但我不确定如何阻止 WordPress 通过进一步的“移至垃圾箱”行动继续前进。这是供参考的代码。

public function register_pre_trash_handler( $product_post_type, $product_comparator_type_meta_key ) {

    $this->product_post_type = $product_post_type;
    $this->product_comparator_type_meta_key = $product_comparator_type_meta_key;

    add_filter( "pre_trash_post", array( $this, "safe_comparator_trash_cb" ), 10, 2 );
  }

  public function safe_comparator_trash_cb( $should_trash, $post ) {

    $product_posts = get_posts( array(
      "post_type" => $this->product_post_type,
      "meta_key" => $this->product_comparator_type_meta_key,
      "meta_value" => $post->ID
    ) );

    if ( ! empty( $product_posts ) ) { // this is the condition. If products exist, don't move the comparator to trash

      $should_trash = null;
    }
  }

仅供参考,不是 PHP 的忠实粉丝,除了修补 WordPress 主题之外从未使用过它。

【问题讨论】:

    标签: php wordpress wordpress-plugin-creation


    【解决方案1】:

    试试wp_trash_post钩子。

    add_action('wp_trash_post', 'prevent_from_trash');
    public function prevent_from_trash($post_id) {
      if (! empty( $product_posts )) { // your condition
        wp_redirect(get_home_url() . "/wp-admin/edit.php?post_type=" . $custom_post_type);
        die();
      }
    }
    

    此解决方案仅防止删除帖子,但不会发出任何警告,也不会注意到它不想删除帖子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2019-02-04
      • 2018-03-20
      • 2023-03-17
      • 2014-08-07
      • 2020-06-12
      相关资源
      最近更新 更多