You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kirki自定义器的选择框中获取WordPress页面ID

在Kirki自定义器中实现WordPress页面下拉选择并获取页面ID

要在Kirki里实现类似Redux的页面选择功能,核心是给SELECT控件的choices参数动态传入页面ID与标题的关联数组,具体操作如下:

  • 注册Kirki选择控件时,通过自定义函数生成页面选项
    先写注册字段的代码,再写一个函数获取所有页面并整理成choices需要的格式:

    // 注册Kirki字段
    Kirki::add_field( 'your_theme_config', array(
        'type'        => 'select',
        'settings'    => 'target_page_id',
        'label'       => esc_attr__( '选择目标页面', 'your-theme-textdomain' ),
        'section'     => 'your_custom_section', // 替换为你的自定义器section ID
        'default'     => '',
        'choices'     => get_kirki_page_choices(),
    ) );
    
    // 生成页面选项的辅助函数
    function get_kirki_page_choices() {
        $pages = get_pages();
        $choices = array( '' => esc_attr__( '请选择页面', 'your-theme-textdomain' ) );
        
        foreach ( $pages as $page ) {
            $choices[ $page->ID ] = $page->post_title;
        }
        
        return $choices;
    }
    
  • 前端调用获取页面ID并生成锚点链接
    用get_theme_mod()拿到保存的页面ID,再通过get_permalink()获取页面URL,拼接锚点即可:

    $selected_page_id = get_theme_mod( 'target_page_id' );
    if ( $selected_page_id ) {
        $page_link = get_permalink( $selected_page_id );
        echo '<a href="' . esc_url( $page_link . '#your-anchor' ) . '">跳转到锚点位置</a>';
    }
    

原理说明:Kirki的SELECT控件choices接受键值对数组,这里把页面ID作为键(方便后续直接获取ID),页面标题作为显示文本,通过get_pages()遍历所有页面生成选项,和Redux的[data]参数效果一致。

内容的提问来源于stack exchange,提问作者Milan Bastola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 16:02:42