我想根据我从SELECT下拉菜单中获取的ID来获取定制POST数据

时间:2019-08-06 作者:cyrus

当我更改select中的值时,我想通过id在同一页上显示特定的post数据。select的代码已经完成,有点像下面的代码,之后我被卡住了,我可以得到关于如何显示数据的任何帮助。

<select class="form-control" id="selectid" name="selectid" > 
<?php 

global $query_string;
//   query_posts (\'posts_per_page=20\');
query_posts(array(
\'post_type\' => \'postname\',
\'posts_per_page\' => \'1000\'
)); 

while (have_posts()) : the_post();                                              
the_title("<option>", "</option>");
endwhile;
?>                                              
</select>
下图可能有助于更好地理解enter image description here

1 个回复
最合适的回答,由SO网友:Eduardo Escobar 整理而成

我认为这应该对你有用:

<?php 
    $posts = get_posts( array(
        \'post_type\'      => \'postname\',
        \'posts_per_page\' => \'1000\'
    ) );
?>
<select class="form-control" id="selectid" name="selectid" > 
    <?php foreach( $posts as $post ) : ?>
        <option value="<?php esc_attr_e( $post->ID ); ?>"><?php esc_html_e( $post->post_title ); ?></option>
    <?php endforeach; ?>                                         
</select>
<!-- Post info -->
<div id="post_info">
</div>
以及javascript部分(您需要将依赖于“jquery”的脚本排队,或者使用另一个支持ajax的库)。

/* script.js, requires jQuery */
;(function($) {
    $(document).ready(function() {
        var postInfoElement = $("#post_info");
        $("#selectid").change(function() {
            var postId = $(this).val();
            $.ajax({
                type: "POST",
                data: "action=get_sigle_post&post_id=" + postId,
                url:  "/wp-admin/admin-ajax.php", // Careful with this, use \'wp_localize_script\' along with the script enqueue method instead.
                success: function(response) {
                    if (!response.success) {
                        // Something went wrong, response.data should contain an error message
                        return false;
                    }
                    var post = response.data;
                    // Do whatever you need to do with "post" and "postInfoElement" variables
                }
            });
        });
    });
})(jQuery);
最后,您需要一个ajax处理程序

// Define this somewhere within your plugin or theme\'s functions file.
add_action( \'wp_ajax_get_sigle_post\', \'my_func_get_sigle_post\' );
add_action( \'wp_ajax_nopriv_get_sigle_post\', \'my_func_get_sigle_post\' ); // For non-logged in users

function my_func_get_sigle_post() {
    $post_id = isset( $_POST[\'post_id\'] ) ? ( int ) $_POST[\'post_id\'] : 0;
    if ( ! $post_id ) wp_send_json_error( \'Invalid post id\' );
    $post = get_post( $post_id );
    if ( ! $post ) wp_send_json_error( \'Could not retrieve the requested post\' );
    // Add or remove $post\'s attributes here

    // Send the ajax response
    wp_send_json_success( $post );
}
不要忘记使用nonce来增强安全性。

相关推荐