首页 > 解决方案 > 如何仅在某些帖子类型上使用 apply_filters 或 add_filter?

问题描述

我正在尝试编辑图像标记,但仅限于一种自定义帖子类型。如何将过滤器仅应用于该帖子类型?

我尝试在函数内部和外部查询帖子类型。

function custom_email_images($html, $id, $caption, $title, $align, $url) {
  $post_type = get_post_type();
  if ( 'email-layout' === $post_type ) {
    $src = wp_get_attachment_url($id);
    $html = '<img src="' . $src . '?w=800" width="415" style="width:415px;max-width:100%">';
  }
  return $html;
}

apply_filters(
  'image_send_to_editor',
  'custom_email_images',
  10,
  6
);

标签: phpwordpress

解决方案


get_post_type() 默认为 get_post_type($post)。该函数本身并不知道全局 $post 变量。

尝试将其添加到顶部的函数中,看看它是否有效:

global $post;

否则尝试 print_r 或回显 get_post_type 并查看它是什么(目前它可能是“假”)。


推荐阅读