如何在自定义PHP文件中执行wordpress函数


How to execute a wordpress function inside custom PHP file

在我的活动主题中有一个用户.php它提供这种 url http://mysite.com/user/username。在用户内部.php我回显了一个包含以下内容的脚本标签

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

我创建了一个文件用户口号.php并将其添加到与user.php相同的级别。在这个文件中,现在我想做的是

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

但是我收到错误,指出我调用的函数未定义。因此,如果我包含一些定义update_user_meta函数的文件,那么我将得到另一个类似的错误,依此类推。执行这样的代码的正确方法是什么?

您需要

包含wp-load.php才能访问自定义文件中的wordpress功能。

建议:请不要包含wp-load。以正确的方式在wordpress中使用ajax。您可以参考这篇文章。

从上面的文章

为什么这是错误的

  1. 你不知道wp-load.php实际上在哪里。插件目录和 wp-content 目录都可以移动 在安装中。所有的WordPress文件都可以在 这种方式,你要四处寻找吗?
  2. 您立即使该服务器上的负载翻了一番。WordPress和它的PHP处理现在必须为每个页面加载两次。 负荷。一次生成页面,然后再次生成您的 生成的 JavaScript。
  3. 你正在动态生成JavaScript。这简直是缓存和速度之类的废话。

尝试WP AJAX

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

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
   }

你需要在那里有整个Wordpress代码库。你最好的选择是制作一个实际的Wordpress插件,这将比这容易得多。

http://codex.wordpress.org/Writing_a_Plugin