简体   繁体   中英

media_sideload_image gets fatal error Call to undefined function wp_get_current_user() in C:\xampp\htdocs\project-name\wp-includes\capabilities.php

Trying to implement media_sideload_image() for the first time from a plugin and getting an error:

Fatal error: Call to undefined function wp_get_current_user() in C:\\xampp\\htdocs\\project-name\\wp-includes\\capabilities.php on line 1441

This is the PHP I am using:

require_once( ABSPATH . '/wp-admin/includes\plugin.php');
require_once( ABSPATH . '/wp-admin/includes\media.php');
require_once( ABSPATH . '/wp-admin/includes\file.php');
require_once( ABSPATH . '/wp-admin/includes\image.php');

$url = "http://wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png";
$post_id = 1;
$desc = "The WordPress Logo";

$image = media_sideload_image($url, $post_id, $desc);

As you can see this is the code from the Wordpress Codex with a bit of addition from forums after I got other errors. However, without luck.

Obviously there is something wrong with the codex code or maybe it's not meant to be used in plugins(?)

What I'm eventually trying to do is get an image and add it to the media library and into the post being edited \\ added directly. I'd appreciate any help I can get. Thanks

If it could help, jsut have the same problems, solved by adding this line :

if(!function_exists('wp_get_current_user')) {
include(ABSPATH . "wp-includes/pluggable.php"); 
}

If you are outside the wp-admin area, you need to add

require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

See https://codex.wordpress.org/Function_Reference/media_sideload_image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM