WordPress开发笔记

WordPress文章形式分类在块主题中的使用

WordPress文章形式分类在块主题中的使用按照以下步骤执行即可。

启用文章形式支持

在主题的functions.php文件中添加以下代码:

// 启用文章形式支持
function my_theme_setup() {
    // 添加文章形式支持
    add_theme_support('post-formats', array(
        'aside',   // 日志
        'gallery', // 相册
        'link',    // 链接
        'image',   // 图像
        'quote',   // 引用
        'status',  // 状态
        'video',   // 视频
        'audio',    // 音频
        'chat'     // 聊天
    ));
}
add_action('after_setup_theme', 'my_theme_setup');

注册定义绑定源

在主题的functions.php文件中添加以下代码:

// Registers block binding sources.
if ( ! function_exists( 'yixiuk2_register_block_bindings' ) ) :
	/**
	 * Registers the post format block binding source.
	 *
	 * @since yixiuk2 1.0
	 *
	 * @return void
	 */
	function yixiuk2_register_block_bindings() {
		register_block_bindings_source(
			'yixiuk2/format',
			array(
				'label'              => _x( '文章格式名称', 'Label for the block binding placeholder in the editor', 'yixiuk2' ),
				'get_value_callback' => 'yixiuk2_format_binding',
			)
		);
	}
endif;
add_action( 'init', 'yixiuk2_register_block_bindings' );

// Registers block binding callback function for the post format name.
if ( ! function_exists( 'yixiuk2_format_binding' ) ) :
	/**
	 * Callback function for the post format name block binding source.
	 *
	 * @since yixiuk2 1.0
	 *
	 * @return string|void Post format name, or nothing if the format is 'standard'.
	 */
	function yixiuk2_format_binding() {
		$post_format_slug = get_post_format();

		if ( $post_format_slug && 'standard' !== $post_format_slug ) {
			return get_post_format_string( $post_format_slug );
		}
	}
endif;

自定义区块应用前台

在块主题的 patterns 文件夹中定义一个 xxx.php 文件,并在核心展示内容的部分添加如下代码:

<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"yixiuk2/format"}}},"fontSize":"small"} -->
<p class="has-small-font-size"></p>
<!-- /wp:paragraph -->

再按照WordPress块主题开发逻辑,完成其他配置。

或者,更详细一些是这样:

在块主题的 patterns 文件夹中定义一个 binding-format.php 文件,并在核心展示内容的部分添加如下代码:

<?php
/**
 * Title: Post format name
 * Slug: twentytwentyfive/binding-format
 * Categories: twentytwentyfive_post-format
 * Description: Prints the name of the post format with the help of the Block Bindings API.
 *
 * @package WordPress
 * @subpackage Twenty_Twenty_Five
 * @since Twenty Twenty-Five 1.0
 */

?>
<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"twentytwentyfive/format"}}},"fontSize":"small"} -->
<p class="has-small-font-size"></p>
<!-- /wp:paragraph -->

以上代码摘自WordPress官方twentytwentyfive主题;

注意:修改代码中头部信息!

之后,主题 parts 文件中的对应文件、theme.json 中的配置,均按照块主题逻辑配置即可,不懂得同学查阅WordPress官方主题 twentytwentyfive 。

之后,我们就完全配置结束。可以通过区块来自由配置布局了。