首页 > 解决方案 > Wordpress 自定义简码输出内容的开始

问题描述

我正在尝试在我的网站上创建一个 ajax 后过滤器,但类别下拉列表一直在内容的开头而不是内联输出。返回; 会正确输出但会结束功能,但 echo 似乎会导致问题。有什么帮助吗?

 <?php 
function blogfiltercustom_function() {
     return '<form action="http://example.com/wp-admin/admin-ajax.php" method="POST" id="filter">' ;}

function blogfilterselect_function(){
if( $terms = get_terms( array(
    'taxonomy' => 'category', // to make it simple I use default categories
    'orderby' => 'name'
) ) ) : 
    // if categories exist, display the dropdown#
    
    echo '<select name="categoryfilter"><option value="">Select category...</option>';
    foreach ( $terms as $term ) :
        echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as an option value
    endforeach;
        echo '</select>';
    
endif; 

        }
    
function blogfilterclose_function(){
    return '<input type="text" name="price_min" placeholder="Min price" />
    <input type="text" name="price_max" placeholder="Max price" />
    <label>
        <input type="radio" name="date" value="ASC" /> Date: Ascending
    </label>
    <label>
        <input type="radio" name="date" value="DESC" selected="selected" /> Date: Descending
    </label>
    <label>
        <input type="checkbox" name="featured_image" /> Only posts with featured images
    </label><button>Apply filter</button>
    <input type="hidden" name="action" value="myfilter">
</form>
<div id="response"></div>'
;}

add_shortcode('blogfiltercustom', 'blogfiltercustom_function');
add_shortcode('blogfilterselect', 'blogfilterselect_function');
add_shortcode('blogfilterclose', 'blogfilterclose_function');

?> 

标签: phpajaxwordpressfunction

解决方案


问题是echo函数应该返回内容而不是回显结果。您可以删除回声并返回最终字符串,也可以使用ob_start()andob_get_clean()

只需添加您的功能

 blogfilterselect_function() {
 ob_start();
 // your Code
return ob_get_clean();
}

推荐阅读