如何从数据库动态加载WordPress内容


How to dynamically load WordPress content from the database?

我为WordPress创建了一个名为Rubrics的自定义帖子类型,这只意味着用户在后端可以看到,所以我用参数'public' => false创建了它,它工作得很好。

在另一个帖子类型(分配)中,我使用以下函数生成自定义标题帖子类型的列表:

<select id="ldrm-select-rubric">    
    <option data-id="0" value="default">Select a Rubric</option>
    <?php 
    $args = array( 'post_type' => 'sfwd-rubrics', 'posts_per_page' => -1 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <option data-id="<?php the_ID(); ?>"><?php the_title(); ?></option>
    <?php endwhile; ?>
</select>

这也很有效,所以现在我有一个标题帖子列表出现在所有作业的编辑页面上。我想知道如何查询标题帖子的内容,而不需要将它们全部加载到页面上。

我知道我可以使用上面的函数查询内容,但是我只想在用户选择后加载从下拉菜单中选择的Rubric的内容,以防止所有其他Rubric也加载。有什么想法可以实现吗?

所以如果我的假设是正确的,您想要保留当前的代码。这就是用标题填充下拉列表。不管你喜欢与否,你已经查询过内容了。从性能的角度来看,最好设置一些变量并使用Javascript来显示正确的变量。另一种选择是使用AJAX并将post id发送到服务器,然后使用所需标题的内容进行响应。我将在这里演示这两个

Performant/simple load once

<?php
// instantiate some variables
$titles = array();
$contents = array();
// set our arrays
foreach (get_posts(array('post_type'=>'sfwd-rubrics','posts_per_page'=>-1)) as $post) {
    $titles[$post->ID] = $post->title;
    $content[$post->ID] = $post->content;
} ?>
<select id="ldrm-select-rubric">
    <?php foreach ($titles as $id => $title): ?>
        <option id="<?= $id ?>"><?= $title ?></option>
    <?php endforeach; ?>
<select>
<?php // time to echo out the contents
foreach ($contents as $id => $content): ?>
    <div id="<?= $id ?>"><?= $content ?></div>
<?php endforeach; ?>
<script type="text/javascript">
    // assuming jQuery is being loaded
    (function($) {
        var $select = $('#ldrm-select-rubric');
        $select.bind('change', function() {
           $(this).find('option').css('display', 'none');
           $('#' + $(this).val()).css('display', 'block');
        });
        $select.trigger('change');
    })(jQuery);
</script>

使用AJAX的更复杂和性能更低的示例

有一些安全特性我就不演示了。这是一个在WordPress中使用AJAX的链接

<?php // somewhere in your php wordpress code
add_action('wp_ajax_rubric_content', function() {
    echo get_post($_REQUEST['id'])->ID;
});
// Below the PHP code in your current question content
<div id="rubric-content"></div>
<script type="text/javascript">
    (function($) {
        $('#ldrm-select-rubric').bind('change', function() {
            $.ajax({
                type: 'GET',
                url: ajaxurl,
                data: {
                    action: 'rubric_content',
                    id: $(this).val(),
                },
                success: function(resp) {
                    $('#rubric-content').html(resp);
                }
            });
        });
    })(jQuery);
</script>

警告:我没有测试上面的代码,但这通常是WP AJAX的工作方式。您需要在服务器代码中添加大量的验证。我强烈推荐前一个示例,因为它更简单、性能更高(查询更少),而且更安全。