Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

wordpress

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

like image 266
Avi Avatar asked Oct 04 '15 14:10

Avi


1 Answers

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

like image 87
quayph Avatar answered Nov 02 '22 23:11

quayph