【问题标题】:Function returning results twice函数返回结果两次
【发布时间】:2015-07-01 14:26:05
【问题描述】:

我正在使用 Wordpress 并构建了一个自定义帖子类型,以从帖子中的逗号分隔列表中返回选项列表,然后在联系表单 7 中创建一组复选框。该函数正在运行,但由于某种原因它两次返回输出。我正在想办法让它只返回一次。

wpcf7_add_shortcode('cargooptions', 'createbox', true);
function createbox(){

    global $post;

    $model = $_GET['mz'];


$args = array(
'post_type' => 'options',
'tax_query' => array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'Opts_category',
        'field'    => 'slug',
        'terms'    => strtolower($model)

    ),  
),

);

$myposts = get_posts( $args );


foreach ( $myposts as $post ) : setup_postdata($post);


        $options = explode(',', get_the_content());

        // output list
        foreach ($options as $key => $value){

            $output .= '<input type="checkbox" name="option_'.$key.'" value="'.$value.'" id="opt'.$key.'" class="optionSelect">';
            $output .= '<label for="opt'.$key.'"  class="span_4 colWrap"><span></span> ' . trim($value) . '</label>';
        }

    endforeach;
return $output;

【问题讨论】:

  • 如果你var_dump在你的函数结束时输出,它输出什么?
  • 你应该得到这个代码的错误;因此,由于您对此没有说任何话,因此您可能关闭了错误报告...
  • 你能告诉我为什么这会导致错误吗?

标签: php wordpress shortcode


【解决方案1】:

请参阅下面的代码。 您需要在循环之前实例化 $output 变量,否则它将在主循环中附加到自身。

foreach ( $myposts as $post ) : setup_postdata($post);


        $options = explode(',', get_the_content());

        // output list
        $output = ''; // add this here so it doesn't append to itself
        foreach ($options as $key => $value){

            $output .= '<input type="checkbox" name="option_'.$key.'" value="'.$value.'" id="opt'.$key.'" class="optionSelect">';
            $output .= '<label for="opt'.$key.'"  class="span_4 colWrap"><span></span> ' . trim($value) . '</label>';
        }

    endforeach;
return $output;

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2012-12-19
    • 2013-07-28
    • 1970-01-01
    相关资源
    最近更新 更多