让WordPress的自定义post type支持post formats

business coffee composition computer

如果要让一个自定义的post type(帖文类型)支持post formats(贴文格式),需要在注册这个post type时设置 ‘supports’ 参数包含 ‘post-formats’。

如果post type已经存在,可能需要使用add_post_type_support()函数来添加支持。这个函数接受两个参数,第一个参数是post type的名字,第二个参数是所要添加的功能。

以下示例,这段代码将 ‘post-formats’ 功能添加到 ‘my_post_type’:

function add_post_formats_to_my_post_type() {
    add_post_type_support( 'my_post_type', 'post-formats' );
}
add_action( 'init', 'add_post_formats_to_my_post_type' );

这段代码应该添加到主题的functions.php文件中(或者是Snippets这样的部署代码的插件中)。这段代码的效果是在WordPress初始化时(’init’ 钩子)添加post type支持。

另外,还需要确保所使用的主题支持post formats。可以在主题的functions.php文件中添加如下代码来启用对post formats的支持:

add_theme_support( 'post-formats', array( 'aside', 'gallery' ) );

上述示例代码启用了 ‘aside’ 和 ‘gallery’ 两种post formats,可以根据需要添加其他的post formats。

比如,若想启用所有可用的post formats,则为:

add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat' ) );

总的来说,需要确保三件事:

  1. 主题支持post formats,
  2. post type支持post formats,
  3. 以及主题对特定的post formats有适当的模板。

Discover more from 山月

Subscribe now to keep reading and get access to the full archive.

Continue reading