2013-09-27 45 views
1

在我的活动主题里面有一个user.php,它服务于这种URL http://mysite.com/user/username。里面user.php的我赞同,内容如下如何在自定义PHP文件中执行wordpress函数

$.ajax({ url: "' . get_theme_root_uri() . '/fray/userslogan.php", 
        data: {"id": ' . $profile['id'] . ', "slogan": el.innerHTML}, 
        type: "post", 
        success: function(status) { alert(status); }      
       }); 

我创建了一个文件userslogan.php,并在同一水平user.php的增加它的脚本标签。里面这个文件现在我想要做的是

<?php 
update_user_meta($_POST['id'], 'slogan', $_POST['slogan']); 
echo 1; 
?> 

但我得到的错误,我调用的函数是未定义的。所以,如果我包含一些定义update_user_meta函数的文件,那么我会得到另一个类似的错误,等等。执行这样的代码的正确方法是什么?

+0

尝试:包括(” ../../../ WP-load.php “); – kidz

+0

检查这个答案http://wordpress.stackexchange.com/a/47059/26906 –

+0

你不应该使用自己的文件来做ajax调用你应该这样做WordPress的方式:http://codex.wordpress.org/AJAX_in_Plugins – janw

回答

3

尝试WP AJAX

1)http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

2)http://codex.wordpress.org/AJAX_in_Plugins

add_action('admin_footer', 'my_action_javascript'); 

function my_action_javascript() { 
    ?> 
    <script type="text/javascript" > 
    jQuery(document).ready(function($) { 

    var data = { 
    action: 'my_action', 
    whatever: 1234 
    }; 

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php 
     $.post(ajaxurl, data, function(response) { 
    alert('Got this from the server: ' + response); 
    }); 
    }); 
    </script> 
    <?php 
    } 

    add_action('wp_ajax_my_action', 'my_action_callback'); 

    function my_action_callback() { 
global $wpdb; // this is how you get access to the database 

$whatever = intval($_POST['whatever']); 

$whatever += 10; 

    echo $whatever; 

die(); // this is required to return a proper result 
    } 
3

您需要包括wp-load.php以访问WordPress的功能自定义文件。

建议:Don’t include wp-load, please.以正确的方式在wordpress中使用ajax。你可以参考这个article

从上面的文章

为什么这是错的

  1. 您不必第一条线索,其中WP-load.php实际上是。在安装中,插件目录和wp-content目录都可以在 附近移动。所有的WordPress文件都可以通过这种方式在 中移动,您是否要为它们搜索?
  2. 您已经立即将该服务器的负载加倍。 WordPress和PHP的处理现在都必须为每个页面加载两次,每次加载时间为 。一旦产生页面,然后再产生你的 生成的javascript。
  3. 您正在生成JavaScript。这只是缓存和速度等的废话。
相关问题