1

我正在编写一个带有 HTML 复选框设置形式的 WordPress 小部件插件。每个复选框对应一个不同的post_type. 这是我的代码:

function form($instance) {
   $defaults   = array( 'num_posts' => 5 );
   $instance   = wp_parse_args( (array) $instance, $defaults );
   $num_posts  = $instance['num_posts'];
   $post_types = get_post_types();
   $instance['post_types'] = $post_types;
   ?>

<p>Number of posts to show: <input class="widefat" name="<?php echo $this->get_field_name( 'num_posts' ); ?>" type="number" value="<?php echo esc_attr( $num_posts ); ?>" /></p>
    <p>Filter by Post Type: <ul>
    <?php foreach ($post_types as $post_type) { ?>
        <li><input name="<?php echo $post_type; ?>" type="checkbox" <?php checked( $post_types, 'on' ); ?> /><label for="<?php echo $post_type; ?>" /><?php echo $post_type; ?></label></li>
    <?php
    } ?>
    </ul></p>

我的问题是,如何$instance为循环中的复选框生成动态名称?我意识到我应该能够做类似的事情$this->get_field_name( 'myname' );,但是如何让它变得动态呢?

注意:上面的代码示例只是输出post_typename 属性而不是使用get_field_name; 这不是解决方案,只是我撞到的一堵墙。

谢谢!

编辑: 我将问题缩小到小部件更新功能,在使用 foreach 循环时似乎不起作用。stackoverflow 上的另一个未解决的问题描述了类似的内容。PHP - Wordpress - 插件小部件更新功能 - 更新数组值 [Foreach 循环不起作用]

这是我的代码(稍作修改),包括更新功能。

    // build the widget settings form
function form( $instance ) {
    $defaults   = array( 'num_posts' => 5 );
    $instance   = wp_parse_args( (array) $instance, $defaults );
    $num_posts  = $instance['num_posts'];

    foreach ( get_post_types() as $post_type ) {
        $post_types_array[$post_type] = $post_type;
    }

    $instance['post_types'] = $post_types_array;
    $post_types = $instance['post_types'];

    echo '<pre>';
    print_r($instance);
    echo '</pre>';
    ?>

        <p>Number of posts to show: <input class="widefat" name="<?php echo $this->get_field_name( 'num_posts' ); ?>" type="number" value="<?php echo esc_attr( $num_posts ); ?>" /></p>
        <p>Filter by Post Type: <ul>
        <?php foreach ( $post_types as $post_type ) { ?>
            <li><input name="<?php echo $this->get_field_name( $post_type ); ?>" type="checkbox" <?php checked( $this->get_field_name( $post_type ) ); ?> /><label for="<?php echo $this->get_field_name( $post_type ); ?>" /><?php echo $post_type; ?></label></li>
        <?php
       } ?>
        </ul></p>

    <?php
}

// save the widget settings
function update( $new_instance, $old_instance ) {
    $instance = $old_instance;
    $instance['num_posts'] = strip_tags( $new_instance['num_posts'] );

    foreach ( $instance['post_types'] as $post_type ) {
        $instance['post_types'][$post_type] = strip_tags( $new_instance['post_types'][$post_type] );
    }

    return $instance;
}
4

0 回答 0