【问题标题】:Unable to get_the_content(); of a post in Wordpress via AJAX无法获取_the_content();通过 AJAX 在 Wordpress 中的帖子
【发布时间】:2012-02-20 17:15:02
【问题描述】:

我正在尝试 ajaxify 我的 Wordpress 主题,我使用 ajax-in-WordPress method,现在我正在尝试通过 functions.php 获取帖子的内容。使用 jQuery,当我执行 alert(data) 时,我得到了“标题”回显,但没有得到我想要的现有帖子的内容(返回 0)。

我做错了什么?

jQuery 部分

$('.ajaxed,.ajaxed a,.menu-item-home a,.menu-item-object-page a').live('click', function(event) {
        event.preventDefault();
        var link = $(this).attr('href');
        var toRemove = MySettings.url;
        var rewritepath = link.replace(toRemove,'');
        var handler = function(data) {
            $('title').html($('title', data).html());
            $('#primary').html($('#primary', data).html());
            $('#primary').hide().fadeIn('slow');
            $.address.title(/>([^<]*)<\/title/.exec(data)[1]);
        };
        $.post(ajax_object.ajaxurl, {
            action: 'ajax_action',
            post_id: $(this).find('input.post_id').attr('value')
        },function(data) {
            alert(data.post_title);
            alert(data.post_content);
        });
        /*$.ajax({
            url: link,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                handler(XMLHttpRequest.responseText);
            },
            success: function(data, textStatus, XMLHttpRequest) {
                handler(data, function(){
                });
            }
        });*/
        $.address.state(MySettings.path).crawlable(true).value(rewritepath);
        return false;
    });

functions.php 部分

<?php
function javascripts() {
    if( !is_admin()){
        $blogurl = get_bloginfo('url');
        $thumbnail_width = get_option('thumbnail_size_w');
        $thumbnail_height = get_option('thumbnail_size_h');
        $path = parse_url(get_bloginfo('siteurl'), PHP_URL_PATH);
        $url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js';
        wp_deregister_script('jquery');
        if (get_transient('google_jquery') == true) {       
            wp_register_script('jquery', $url, array(), null, true);
        } 
        else {
            $resp = wp_remote_head($url);
            if (!is_wp_error($resp) && 200 == $resp['response']['code']) {
                set_transient('google_jquery', true, 60 * 5);
                wp_register_script('jquery', $url, array(), null, true);
            } 
            else {
                set_transient('google_jquery', false, 60 * 5);
                $url = get_bloginfo('wpurl') . '/wp-includes/js/jquery/jquery.js';
                wp_register_script('jquery', $url, array(), '1.7', true);
            }
        }
        wp_enqueue_script('plugins.js', get_bloginfo('template_directory') . "/js/plugins.js" , array('jquery'));
        wp_enqueue_script('ajax-script', get_bloginfo('template_directory') . "/js/scripts.js", array('jquery'));
        wp_localize_script('ajax-script', 'ajax_object', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
        wp_localize_script('jquery', 'MySettings', array('width' => $thumbnail_width,'height' => $thumbnail_height,'url' => $blogurl,'path' => $path));
    }
}
add_action('wp_enqueue_scripts', 'javascripts');
add_action('wp_ajax_ajax_action', 'ajax_action_stuff'); // ajax for logged in users
add_action('wp_ajax_nopriv_ajax_action', 'ajax_action_stuff'); // ajax for not logged in users
function ajax_action_stuff() {
    $post_id = $_POST['post_id'];
    update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
    $post_data = get_post($post_id);
    echo json_encode($post_data);
}
?>

我做错了什么?谢谢

【问题讨论】:

    标签: ajax wordpress jquery


    【解决方案1】:

    如果没有看到代码的整个范围,您可能会在 The Loop 的上下文之外调用 get_the_content()。如果是这样,则该函数无法识别您要为其检索内容的哪个帖子。尝试以这种方式组织函数:

    function ajax_action_stuff() {
        $post_id = $_POST['post_id'];
        update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
        $post_data = get_post($post_id);
        $title = $post_data->post_title;
        $content = $post_data->post_content;
        echo $title;
        echo $content;
    }
    

    这里我们使用get_post() 来返回一个包含所有帖子数据的对象。

    您创建的 jQuery 函数...

    function(data) {
        alert(data);
    });
    

    ... 本质上应该在 data 对象中包含一个字符串,其中包含您的标题和内容。

    这里有一个建议,如果您愿意,您可以如何以更有条理的方式返回您的数据。

    “数据”对象(这是您在 php 函数 ajax_action_stuff() 中回显的内容)只是一个字符串值。但问题是,数据的结构并没有让 jQuery 完全理解和充分发挥其潜力。如果您更改 php 函数以返回 JSON 对象,那么您可以单独使用 jQuery 中的所有属性。我会告诉你如何......

    function ajax_action_stuff() {
        $post_id = $_POST['post_id'];
        update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
        $post_data = get_post($post_id);
        echo json_encode($post_data);
    }
    

    然后在 jQuery 函数中,您可以像这样访问每个属性:

    $.post(ajax_object.ajaxurl, {
        action: 'ajax_action',
        post_id: $(this).find('input.post_id').attr('value')
    },function(data) {
        alert(data.post_title);
        alert(data.post_content);
    });
    

    查看get_post() 函数,了解您可以使用的所有属性。

    【讨论】:

    • 我已经更新了问题,添加了更多代码和信息...我得到未定义的结果(2 个警告框)。
    • 让我们看看能否找出故障发生的位置...如果您使用 Firefox 和 Firebug,请打开“控制台”选项卡并确保已启用“控制台”。然后单击触发 AJAX 调用的锚点。您应该会在控制台中看到包含您的请求的新帖子和响应。帖子数据是否包含您期望的所有数据?反应如何?您应该在帖子中看到 post_id 变量和值,以及包含所有帖子数据的 JSON 编码响应。你走到这一步了吗?
    • 锚是标题...对不起;-)
    • 啊,我看到一个问题是我们实际上并没有像我们想象的那样传递帖子 ID。注意读取post_id: $(this).find('input.post_id').attr('value') 的行。在您的页面中,我没有看到任何带有 post_id 类的输入。所以 jQuery 试图获取该值但找不到它。它最终没有向 PHP 传递任何东西。
    • 好的,非常感谢...我现在看到 JSON 响应,但仍未定义。
    【解决方案2】:

    您没有告诉get_the_content() 要检索哪个帖子的内容。在内部,此函数检查全局 $post 对象并过滤该对象的内容。

    所以把你的 ajax 函数改成这样:

    function ajax_action_stuff() {
        global $post;
    
        $post_id = $_POST[ 'post_id' ];
        update_post_meta( $post_id, 'post_key', 'meta_value' );
    
        $post = get_post( $post_id );
    
        $title = 'title';
        $content = get_the_content();
    
        echo $title;
        echo $content;
    }
    

    这将使用您传入的 ID 在数据库中查询特定帖子并填充全局 $post 对象。现在,get_the_content() 甚至get_the_title() 应该可以正常运行了。

    【讨论】:

    • 对我不起作用。我得到:注意:尝试在第 279 行的 /var/www/vhosts/xxx.com/httpdocs/wp-includes/post-template.php 中获取非对象的属性
    猜你喜欢
    • 2012-08-06
    • 2017-04-23
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多