簡體   English   中英

使用復選框獲取按元值發布的帖子

[英]Get Posts by Meta Values using checkbox

在我的wordpress主題中,我在邊欄中創建了兩個復選框以用於自定義字段值。 Apple和Nokia是鍵名Brand的值。

現在我需要在選中一個或多個復選框時顯示所有相關帖子?

這是輸入代碼,

<form>
<input type="checkbox" name="mobile" value="nokia"
<?php  
$args = array (
'meta_query'    => array(
    array(
        'key'   => 'brand',
        'value' => 'nokia'  
    ),
 ),
);
$query = new WP_Query( $args );
?>/> Nokia <br>


<input type="checkbox" name="mobile" value="apple"
<?php  
$args = array (
'meta_query'    => array(
    array(
        'key'   => 'brand',
        'value' => 'apple'  
    ),
 ),
);
?>/> Apple <br>
</form>

此查詢用於獲取帖子,如何在模板文件中使用它來顯示復選框結果?

<?php $query = new WP_Query( $args );
     if ( $query->have_posts() ) {
 while ( $query->have_posts() ) {
    $query->the_post();
   get_template_part('content');
 }
} else {
}
wp_reset_postdata();
?>

這是代碼

這應該在您的模板中

    <form id='test'>
<input type="checkbox" name="t[]" value="Nokia" class="br">
<input type="checkbox" name="t[]" value="Sony" class="br">
<div class="mobile_brand">

</div>
</form>
<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('.br').click(function(){
            jQuery('.contents').remove();
            var checked = jQuery('#test').serialize();
            jQuery.ajax({
                url:"<?php echo admin_url('admin-ajax.php'); ?>",
                data:"action=call_post&"+checked,
                success:function(obj){
                     var render_data = "<div class='contents'>";

                    // This is to watch your json object
                    console.log(obj);   

                    for(var i=0;i<obj.length;i++)
                    {
                        console.log(obj[i].post_title);
                        render_data+="<h4>"+obj[i].post_title+"</h4>";
                        render_data+="<p>"+obj[i].post_content+"</p>";
                    }
                    render_data+="</div>";
                    jQuery(render_data).appendTo('.mobile_brand');

                }
            });
        })
    });
</script>

這應該在您的functions.php

add_action('wp_ajax_call_post','call_post');
add_action('wp_ajax_nopriv_call_post','call_post');
function call_post(){
    $test = $_REQUEST['mobile'];

    $args = array(
        'post_type'  => 'post',
        'meta_query' => array(
            array(
                'key'     => 'brand',
                'value'   => $test,
                // 'compare' => 'IN',
            ),
        ),
    );

$query = new WP_Query( $args );
wp_send_json($query->posts);

}

這只是給您的示例代碼。 您需要通過迭代JSON來呈現數據。

您正在尋找get_post_meta 如以下示例所示,它在循環中使用。 您的循環可能位於包含“內容”模板部分的文件中。

get_post_meta( get_the_ID(), 'brand', true );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM