如何使用 XMLRPC 在 WordPress 中创建带有照片的新帖子?

发布于 2024-12-07 11:59:51 字数 2120 浏览 0 评论 0原文

有人知道如何使用 XMLRPC 在 WordPress 中创建带有照片的新帖子吗?

我可以单独创建新帖子并上传新图片,但看起来无法将上传的照片附加到创建的帖子中。邮政?

以下是我当前使用的代码。

<?php
DEFINE('WP_XMLRPC_URL', 'http://www.blog.com/xmlrpc.php');
DEFINE('WP_USERNAME', 'username');
DEFINE('WP_PASSWORD', 'password');

require_once("./IXR_Library.php");
$rpc = new IXR_Client(WP_XMLRPC_URL);
$status = $rpc->query("system.listMethods"); // method name
if(!$status){
    print "Error (".$rpc->getErrorCode().") : ";
    print $rpc->getErrorMessage()."\n";
    exit;
}

$content['post_type'] = 'post'; // post title
$content['title'] = 'Post Title '.date("F j, Y, g:i a"); // post title
$content['categories'] = array($response[1]['categoryName']); // psot categories
$content['description'] = '<p>Hello World!</p>'; // post body
$content['mt_keywords'] = 'tag keyword 1, tag keyword 2, tag keyword 3'; // post tags
$content['mt_allow_comments'] = 1; // allow comments
$content['mt_allow_pings'] = 1; // allow pings
$content['custom_fields'] = array(array('key'=>'Key Name', 'value'=>'Value One')); // custom fields
$publishBool = true;

if(!$rpc->query('metaWeblog.newPost', '', WP_USERNAME, WP_PASSWORD, $content, $publishBool)){
    die('An error occurred - '.$rpc->getErrorCode().":".$rpc->getErrorMessage());
}
$postID = $rpc->getResponse();
echo 'POST ID: '.$postID.'<br/>';

if($postID){ // if post has successfully created

    $fs = filesize(dirname(__FILE__).'/image.jpg');
    $file = fopen(dirname(__FILE__).'/image.jpg', 'rb');
    $filedata = fread($file, $fs);
    fclose($file);

    $data = array(
        'name'  => 'image.jpg',
        'type'  => 'image/jpg',
        'bits'  => new IXR_Base64($filedata),
        false // overwrite
    );

    $status = $rpc->query(
        'metaWeblog.newMediaObject',
        $postID,
        WP_USERNAME,
        WP_PASSWORD,
        $data
    );
    echo print_r($rpc->getResponse()); // Array ( [file] => image.jpg [url] => http://www.blog.com/wp-content/uploads/2011/09/image.jpg [type] => image/jpg )
}
?>

Anyone knows how to create new post with photo attached in WordPress using XMLRPC?

I am able to create new post and upload new picture separately, but looks like there is no way to attach the uploaded photo to the created post?

Below is the codes I'm currently using.

<?php
DEFINE('WP_XMLRPC_URL', 'http://www.blog.com/xmlrpc.php');
DEFINE('WP_USERNAME', 'username');
DEFINE('WP_PASSWORD', 'password');

require_once("./IXR_Library.php");
$rpc = new IXR_Client(WP_XMLRPC_URL);
$status = $rpc->query("system.listMethods"); // method name
if(!$status){
    print "Error (".$rpc->getErrorCode().") : ";
    print $rpc->getErrorMessage()."\n";
    exit;
}

$content['post_type'] = 'post'; // post title
$content['title'] = 'Post Title '.date("F j, Y, g:i a"); // post title
$content['categories'] = array($response[1]['categoryName']); // psot categories
$content['description'] = '<p>Hello World!</p>'; // post body
$content['mt_keywords'] = 'tag keyword 1, tag keyword 2, tag keyword 3'; // post tags
$content['mt_allow_comments'] = 1; // allow comments
$content['mt_allow_pings'] = 1; // allow pings
$content['custom_fields'] = array(array('key'=>'Key Name', 'value'=>'Value One')); // custom fields
$publishBool = true;

if(!$rpc->query('metaWeblog.newPost', '', WP_USERNAME, WP_PASSWORD, $content, $publishBool)){
    die('An error occurred - '.$rpc->getErrorCode().":".$rpc->getErrorMessage());
}
$postID = $rpc->getResponse();
echo 'POST ID: '.$postID.'<br/>';

if($postID){ // if post has successfully created

    $fs = filesize(dirname(__FILE__).'/image.jpg');
    $file = fopen(dirname(__FILE__).'/image.jpg', 'rb');
    $filedata = fread($file, $fs);
    fclose($file);

    $data = array(
        'name'  => 'image.jpg',
        'type'  => 'image/jpg',
        'bits'  => new IXR_Base64($filedata),
        false // overwrite
    );

    $status = $rpc->query(
        'metaWeblog.newMediaObject',
        $postID,
        WP_USERNAME,
        WP_PASSWORD,
        $data
    );
    echo print_r($rpc->getResponse()); // Array ( [file] => image.jpg [url] => http://www.blog.com/wp-content/uploads/2011/09/image.jpg [type] => image/jpg )
}
?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

明媚如初 2024-12-14 11:59:51

我参与过 WordPress 网站(我现在的雇主使用其中的 3 个),每天都会发布大量内容,这迫使我使用我最擅长的东西——脚本!

它们基于 PHP,并且快速且易于使用和部署。还有安全性?只需使用 .htaccess 来保护它。

根据研究,XMLRPC 在文件方面是 WordPress 真正糟糕的一件事。上传文件后,您无法将该附件关联到特定帖子!我知道,这很烦人。

所以我决定自己想办法。我花了一周时间才整理出来。您需要对符合 XMLRPC 的发布客户端进行 100% 的控制,否则这对您来说毫无意义!

您将需要,从您的 WordPress 安装:

  • class-IXR.php,位于 /wp-admin/includes
  • class-wp-xmlrpc-server.php,位于 /wp-includes

如果您制作,则需要 class-IXR.php你自己的发帖工具,就像我一样。他们有正确工作的 Base64 编码器。不要相信 PHP 附带的那个。

您还需要在编程方面有一定的经验才能理解这一点。我会尽力说得更清楚。

  1. 修改class-wp-xmlrpc-server.php

    • 通过 ftp 将其下载到您的计算机上。备份一份副本,以防万一。
    • 在文本编辑器中打开文件。如果它没有格式化(通常应该是这样,否则,他们使用的是unix类型的回车符)在其他地方打开它或使用ultraedit之类的东西。
    • 注意mw_newMediaObject函数。这是我们的目标。这里有一点注意; WordPress 借鉴了博客和活字印刷的功能。尽管 WordPress 也有一个独特的 xmlrpc 类集,但它们选择保持通用功能,以便无论使用什么平台它们都可以工作。
    • 查找函数mw_newMediaObject($args)。通常,这应该位于第 2948 行。请注意文本编辑器的状态栏,以查找您所在的行号。如果仍然找不到它,请使用文本编辑器的搜索/查找功能进行查找。< /里>
    • 向下滚动一点,您应该看到如下所示的内容:

       $name = sanitize_file_name( $data['name'] );
       $type = $data['type'];
       $bits = $data['bits'];
      
    • 在 $name 变量之后,我们将添加一些内容。见下文。

       $name = sanitize_file_name( $data['name'] );
       $post = $data['post']; //要附加的帖子 ID。
       $type = $data['type'];
       $bits = $data['bits'];
      

      注意新的 $post 变量。这意味着每当您发出新的文件上传请求时,现在都可以附加“post”参数。

      如何查找您的帖子编号取决于您如何使用符合 xmlrpc 的客户端添加帖子。通常,您应该通过发布获得此结果。它是一个数值。

      编辑完上述内容后,就可以转到第 3000 行了。

      //构造附件数组
      // 附加到 post_id 0
      $post_id = 0;
      $附件=数组(
          'post_title'=>; $名称,
          'post_content'=>; '',
          'post_type'=>; '依恋',
          'post_parent'=>; $post_id,
          'post_mime_type' =>; $类型,
          '指导' => $上传['网址']
      );
      
    • 这就是为什么没有图像与任何帖子关联的原因! post_parent 参数始终默认为 0!
      以后情况不会再这样了。

      //构造附件数组
      // 附加到 post_id 0
      $post_id = $post;
      $附件=数组(
          'post_title'=>; $名称,
          'post_content'=>; '',
          'post_type'=>; '依恋',
          'post_parent'=>; $post_id,
          'post_mime_type' =>; $类型,
          '指导' => $上传['网址']
      );
      

      $post_id 现在占用 $post 的值,该值来自 xmlrpc 请求。一旦将其提交到附件,它将与您想要的任何帖子相关联!

      这个可以改进。可以分配默认值,这样如果没有输入值,事情就不会被破坏。虽然在我这边,我把默认值放在了我的客户端上,除了我之外没有其他人访问XMLRPC接口。

    • 完成更改后,保存文件并将其重新上传到您找到它的同一路径中。再次强调,一定要做好备份。

      警惕影响此模块的 WordPress 更新。如果发生这种情况,您需要再次重新应用此编辑!

  2. 在您的 PHP 类型编辑器中包含 class-IXR.php。如果您使用其他东西,那么我无法帮助您。 :(

希望这对某些人有帮助。

I've been involved in WordPress sites (my current employer uses 3 of these) and posting stuff daily and by the bulk has forced me to use what I do best-- scripts!

They're PHP-based and are quick and easy to use and deploy. And security? Just use .htaccess to secure it.

As per research, XMLRPC when it comes to files is one thing wordpress really sucks at. Once you upload a file, you can't associate that attachment to a particular post! I know, it's annoying.

So I decided to figure it out for myself. It took me a week to sort it out. You will need 100% control over your publishing client that is XMLRPC compliant or this won't mean anything to you!

You will need, from your WordPress installation:

  • class-IXR.php, located in /wp-admin/includes
  • class-wp-xmlrpc-server.php, located in /wp-includes

class-IXR.php will be needed if you craft your own posting tool, like me. They have the correctly-working base64 encoder. Don't trust the one that comes with PHP.

You also need to be somewhat experienced in programming to be able to relate to this. I will try to be clearer.

  1. Modify class-wp-xmlrpc-server.php

    • Download this to your computer, through ftp. Backup a copy, just in case.
    • Open the file in a text editor. If it doesn't come formatted, (typically it should, else, it's unix-type carriage breaks they are using) open it elsewhere or use something like ultraedit.
    • Pay attention to the mw_newMediaObject function. This is our target. A little note here; WordPress borrows functionality from blogger and movabletype. Although WordPress also has a unique class sets for xmlrpc, they choose to keep functionality common so that they work no matter what platform is in use.
    • Look for the function mw_newMediaObject($args). Typically, this should be in line 2948. Pay attention to your text editor's status bar to find what line number you are in. If you can't find it still, look for it using the search/find function of your text editor.
    • Scroll down a little and you should have something that looks like this:

       $name = sanitize_file_name( $data['name'] );
       $type = $data['type'];
       $bits = $data['bits'];
      
    • After the $name variable, we will add something. See below.

       $name = sanitize_file_name( $data['name'] );
       $post = $data['post']; //the post ID to attach to.
       $type = $data['type'];
       $bits = $data['bits'];
      

      Note the new $post variable. This means whenever you will make a new file upload request, a 'post' argument will now be available for you to attach.

      How to find your post number depends on how you add posts with an xmlrpc-compliant client. Typically, you should obtain this as a result from posting. It is a numeric value.

      Once you've edited the above, it's time to move on to line 3000.

      // Construct the attachment array
      // attach to post_id 0
      $post_id = 0;
      $attachment = array(
          'post_title' => $name,
          'post_content' => '',
          'post_type' => 'attachment',
          'post_parent' => $post_id,
          'post_mime_type' => $type,
          'guid' => $upload[ 'url' ]
      );
      
    • So here's why no image is associated to any post! It is always defaulted to 0 for the post_parent argument!
      That's not gonna be the case anymore.

      // Construct the attachment array
      // attach to post_id 0
      $post_id = $post;
      $attachment = array(
          'post_title' => $name,
          'post_content' => '',
          'post_type' => 'attachment',
          'post_parent' => $post_id,
          'post_mime_type' => $type,
          'guid' => $upload[ 'url' ]
      );
      

      $post_id now takes up the value of $post, which comes from the xmlrpc request. Once this is committed to the attachment, it will be associated to whatever post you desire!

      This can be improved. A default value can be assigned so things don't get broken if no value is entered. Although in my side, I put the default value on my client, and no one else is accessing the XMLRPC interface but me.

    • With the changes done, save your file and re-upload it in the same path where you found it. Again, make sure to make backups.

      Be wary of WordPress updates that affects this module. If that happens, you need to reapply this edit again!

  2. Include class-IXR.php in your PHP-type editor. If you're using something else, well, I can't help you there. :(

Hope this helps some people.

李白 2024-12-14 11:59:51

当您发帖时,WordPress 会在帖子中扫描 IMG 标签。
如果 WP 找到该图像,则会将其加载到其媒体库中。如果正文中有图像,它会自动将其附加到帖子中。

基本上,您必须:

  • 首先发布媒体(图像)
  • 获取其 URL,
  • 在帖子正文中包含带有 IMG 标签的图像的 URL。
  • 然后创建帖子

这是一些示例代码。它需要错误处理和更多文档。

$admin ="***";
$userid ="****";
$xmlrpc = 'http://localhost/web/blog/xmlrpc.php';
include '../blog/wp-includes/class-IXR.php';
$client = new IXR_Client($xmlrpc);

$author         =   "test";    
$title          =   "Test Posting";
$categories     =   "chess,coolbeans";
$body           =   "This is only a test disregard </br>";

$tempImagesfolder = "tempImages";
$img = "1338494719chessBoard.jpg";


$attachImage = uploadImage($tempImagesfolder,$img);
$body .= "<img src='$attachImage' width='256' height='256' /></a>";

createPost($title,$body,$categories,$author);

/*
*/
function createPost($title,$body,$categories,$author){
    global $username, $password,$client;
    $authorID =  findAuthor($author); //lookup id of author

    /*$categories is a list seperated by ,*/
    $cats = preg_split('/,/', $categories, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($cats as $key => $data){
        createCategory($data,"","");
    }

    //$time = time();
    //$time += 86400;
    $data = array(
        'title' => $title,
        'description' => $body,
        'dateCreated' => (new IXR_Date(time())),
        //'dateCreated' => (new IXR_Date($time)),  //publish in the future
        'mt_allow_comments' => 0, // 1 to allow comments
        'mt_allow_pings' => 0,// 1 to allow trackbacks
        'categories' => $cats,
        'wp_author_id' => $authorID     //id of the author if set       
    );
    $published = 0; // 0 - draft, 1 - published
    $res = $client->query('metaWeblog.newPost', '', $username, $password, $data, $published);
}

/*
*/
function uploadImage($tempImagesfolder,$img){
    global $username, $password,$client;
    $filename = $tempImagesfolder ."/" . $img;

    $fs = filesize($filename);   
    $file = fopen($filename, 'rb');  
    $filedata = fread($file, $fs);    
    fclose($file); 

    $data = array(
        'name'  => $img, 
        'type'  => 'image/jpg',  
        'bits'  => new IXR_Base64($filedata), 
        false //overwrite
    );

    $res = $client->query('wp.uploadFile',1,$username, $password,$data);
    $returnInfo = $client->getResponse();

    return $returnInfo['url'];     //return the url of the posted Image
}

/*
*/
function findAuthor($author){
    global $username, $password,$client;
    $client->query('wp.getAuthors ', 0, $username, $password);
    $authors = $client->getResponse();
    foreach ($authors as $key => $data){
        //  echo $authors[$key]['user_login'] . $authors[$key]['user_id'] ."</br>";
        if($authors[$key]['user_login'] == $author){
            return $authors[$key]['user_id'];
        }
    }
    return "not found";
}

/*
*/
function createCategory($catName,$catSlug,$catDescription){
    global $username, $password,$client;
    $res = $client->query('wp.newCategory', '', $username, $password,
        array(
            'name' => $catName,
            'slug' => $catSlug,
            'parent_id' => 0,
            'description' => $catDescription
        )
    );
}

When you post, WordPress will scan at the post for IMG tags.
If WP finds the image, it's loaded in it's media library. If there's an image in the body, it will automatically attached it to the post.

Basically you have to:

  • post the media (image) first
  • Grab its URL
  • include the URL of the image with a IMG tag in the body of your post.
  • then create the post

Here is some sample code. It needs error handling, and some more documentation.

$admin ="***";
$userid ="****";
$xmlrpc = 'http://localhost/web/blog/xmlrpc.php';
include '../blog/wp-includes/class-IXR.php';
$client = new IXR_Client($xmlrpc);

$author         =   "test";    
$title          =   "Test Posting";
$categories     =   "chess,coolbeans";
$body           =   "This is only a test disregard </br>";

$tempImagesfolder = "tempImages";
$img = "1338494719chessBoard.jpg";


$attachImage = uploadImage($tempImagesfolder,$img);
$body .= "<img src='$attachImage' width='256' height='256' /></a>";

createPost($title,$body,$categories,$author);

/*
*/
function createPost($title,$body,$categories,$author){
    global $username, $password,$client;
    $authorID =  findAuthor($author); //lookup id of author

    /*$categories is a list seperated by ,*/
    $cats = preg_split('/,/', $categories, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($cats as $key => $data){
        createCategory($data,"","");
    }

    //$time = time();
    //$time += 86400;
    $data = array(
        'title' => $title,
        'description' => $body,
        'dateCreated' => (new IXR_Date(time())),
        //'dateCreated' => (new IXR_Date($time)),  //publish in the future
        'mt_allow_comments' => 0, // 1 to allow comments
        'mt_allow_pings' => 0,// 1 to allow trackbacks
        'categories' => $cats,
        'wp_author_id' => $authorID     //id of the author if set       
    );
    $published = 0; // 0 - draft, 1 - published
    $res = $client->query('metaWeblog.newPost', '', $username, $password, $data, $published);
}

/*
*/
function uploadImage($tempImagesfolder,$img){
    global $username, $password,$client;
    $filename = $tempImagesfolder ."/" . $img;

    $fs = filesize($filename);   
    $file = fopen($filename, 'rb');  
    $filedata = fread($file, $fs);    
    fclose($file); 

    $data = array(
        'name'  => $img, 
        'type'  => 'image/jpg',  
        'bits'  => new IXR_Base64($filedata), 
        false //overwrite
    );

    $res = $client->query('wp.uploadFile',1,$username, $password,$data);
    $returnInfo = $client->getResponse();

    return $returnInfo['url'];     //return the url of the posted Image
}

/*
*/
function findAuthor($author){
    global $username, $password,$client;
    $client->query('wp.getAuthors ', 0, $username, $password);
    $authors = $client->getResponse();
    foreach ($authors as $key => $data){
        //  echo $authors[$key]['user_login'] . $authors[$key]['user_id'] ."</br>";
        if($authors[$key]['user_login'] == $author){
            return $authors[$key]['user_id'];
        }
    }
    return "not found";
}

/*
*/
function createCategory($catName,$catSlug,$catDescription){
    global $username, $password,$client;
    $res = $client->query('wp.newCategory', '', $username, $password,
        array(
            'name' => $catName,
            'slug' => $catSlug,
            'parent_id' => 0,
            'description' => $catDescription
        )
    );
}
月光色 2024-12-14 11:59:51

调用方法 metaWeblog.newMediaObject 后,我们需要编辑数据库中的图像条目以添加父项(之前使用 metaWeblog.newPost 创建的帖子)。

如果我们尝试使用 metaWeblog.editPost,它会抛出错误 401,这表明

// Use wp.editPost to edit post types other than post and page.
if ( ! in_array( $postdata[ 'post_type' ], array( 'post', 'page' ) ) )
    return new IXR_Error( 401, __( 'Invalid post type' ) );

解决方案是调用 wp.editPost,它采用以下参数:

$blog_id        = (int) $args[0];
$username       = $args[1];
$password       = $args[2];
$post_id        = (int) $args[3];
$content_struct = $args[4];

因此,在 newMediaObject 之后,我们执行以下操作:

$status = $rpc->query(
    'metaWeblog.newMediaObject',
    $postID,
    WP_USERNAME,
    WP_PASSWORD,
    $data
);
$response = $rpc->getResponse();
if( isset($response['id']) ) {
    // ATTACH IMAGE TO POST
    $image['post_parent'] = $postID;
    if( !$rpc->query('wp.editPost', '1', WP_USERNAME, WP_PASSWORD, $response['id'], $image)) {
        die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
    }
    echo 'image: ' . $rpc->getResponse();

    // SET FEATURED IMAGE
    $updatePost['custom_fields'] = array( array( 'key' => '_thumbnail_id', 'value' => $response['id'] ) );
    if( !$rpc->query( 'metaWeblog.editPost', $postID, WP_USERNAME, WP_PASSWORD, $updatePost, $publishBool ) ) {
        die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
    }
    echo 'update: ' . $rpc->getResponse();
}

我使用了 Incutio用于 PHP 的 XML-RPC 库进行测试,其余代码与问题中完全相同。

After calling the method metaWeblog.newMediaObject, we need to edit the image entry on the database to add a parent (the previously created post with metaWeblog.newPost).

If we try with metaWeblog.editPost, it throws an error 401, which indicates that

// Use wp.editPost to edit post types other than post and page.
if ( ! in_array( $postdata[ 'post_type' ], array( 'post', 'page' ) ) )
    return new IXR_Error( 401, __( 'Invalid post type' ) );

The solution is to call wp.editPost, which takes the following arguments:

$blog_id        = (int) $args[0];
$username       = $args[1];
$password       = $args[2];
$post_id        = (int) $args[3];
$content_struct = $args[4];

So, just after newMediaObject, we do:

$status = $rpc->query(
    'metaWeblog.newMediaObject',
    $postID,
    WP_USERNAME,
    WP_PASSWORD,
    $data
);
$response = $rpc->getResponse();
if( isset($response['id']) ) {
    // ATTACH IMAGE TO POST
    $image['post_parent'] = $postID;
    if( !$rpc->query('wp.editPost', '1', WP_USERNAME, WP_PASSWORD, $response['id'], $image)) {
        die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
    }
    echo 'image: ' . $rpc->getResponse();

    // SET FEATURED IMAGE
    $updatePost['custom_fields'] = array( array( 'key' => '_thumbnail_id', 'value' => $response['id'] ) );
    if( !$rpc->query( 'metaWeblog.editPost', $postID, WP_USERNAME, WP_PASSWORD, $updatePost, $publishBool ) ) {
        die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() );
    }
    echo 'update: ' . $rpc->getResponse();
}

I've used the Incutio XML-RPC Library for PHP to test and the rest of the code is exactly as in the question.

[浮城] 2024-12-14 11:59:51

以下是一些示例代码,用于附加 WordPress 不支持的路径中的图像 (wp-content)

<?php
function attach_wordpress_images($productpicture,$newid)
{
    include('../../../../wp-load.php');
    $upload_dir = wp_upload_dir();
    $dirr = $upload_dir['path'].'/';

    $filename = $dirr . $productpicture;                    
    # print "the path is : $filename \n";                    
    # print "Filnamn: $filename \n";                
    $uploads = wp_upload_dir(); // Array of key => value pairs
    # echo $uploads['basedir'] . '<br />';
    $productpicture = str_replace('/uploads','',$productpicture);
    $localfile =  $uploads['basedir'] .'/' .$productpicture;
    #  echo "Local path = $localfile \n";         

    if (!file_exists($filename))
    {
        echo "hittade inte $filename !";
        die ("no image for flaska $id $newid !");                                                   
    }
    if (!copy($filename, $localfile)) 
    {
        wp_delete_post($newid);
        echo  "Failed to copy the file $filename to $localfile ";
        die("Failed to copy the file $filename to $localfile ");
    }

    $wp_filetype = wp_check_filetype(basename($localfile), null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($localfile)),
        'post_content' => '',
        'post_status' => 'inherit'
        );
    $attach_id = wp_insert_attachment( $attachment, $localfile, $newid );

    // you must first include the image.php file
    // for the function wp_generate_attachment_metadata() to work

    require_once(ABSPATH . 'wp-admin/includes/image.php');        
    $attach_data = wp_generate_attachment_metadata( $attach_id, $localfile );
    wp_update_attachment_metadata( $attach_id, $attach_data );  
}
?>

Here's some sample code to attach an image from a path not supported by WordPress (wp-content)

<?php
function attach_wordpress_images($productpicture,$newid)
{
    include('../../../../wp-load.php');
    $upload_dir = wp_upload_dir();
    $dirr = $upload_dir['path'].'/';

    $filename = $dirr . $productpicture;                    
    # print "the path is : $filename \n";                    
    # print "Filnamn: $filename \n";                
    $uploads = wp_upload_dir(); // Array of key => value pairs
    # echo $uploads['basedir'] . '<br />';
    $productpicture = str_replace('/uploads','',$productpicture);
    $localfile =  $uploads['basedir'] .'/' .$productpicture;
    #  echo "Local path = $localfile \n";         

    if (!file_exists($filename))
    {
        echo "hittade inte $filename !";
        die ("no image for flaska $id $newid !");                                                   
    }
    if (!copy($filename, $localfile)) 
    {
        wp_delete_post($newid);
        echo  "Failed to copy the file $filename to $localfile ";
        die("Failed to copy the file $filename to $localfile ");
    }

    $wp_filetype = wp_check_filetype(basename($localfile), null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($localfile)),
        'post_content' => '',
        'post_status' => 'inherit'
        );
    $attach_id = wp_insert_attachment( $attachment, $localfile, $newid );

    // you must first include the image.php file
    // for the function wp_generate_attachment_metadata() to work

    require_once(ABSPATH . 'wp-admin/includes/image.php');        
    $attach_data = wp_generate_attachment_metadata( $attach_id, $localfile );
    wp_update_attachment_metadata( $attach_id, $attach_data );  
}
?>
GRAY°灰色天空 2024-12-14 11:59:51

几个月前我就不得不这样做。这是可能的,但它不仅是黑客和无证的,我必须挖掘 WordPress 源代码才能弄清楚。我当时写的:

绝对没有记录的一件事是将图像附加到帖子的方法。经过一番挖掘,我发现了 Attach_uploads(),这是每次通过 xml-rpc 创建或编辑帖子时 WordPress 都会调用的函数。它的作用是搜索未附加的媒体对象列表,并查看新的/编辑的帖子是否包含指向它们的链接。由于我试图附加图像以便主题的画廊可以使用它们,所以我不一定想链接到帖子中的图像,也不想编辑 WordPress。所以我最终做的是将图像 url 包含在 html 注释中。 -- daniru.com

就像我说的,很乱,但是我到处寻找更好的方法,但我有理由确信不存在。

I had to do this several months ago. It is possible but not only is it hacky and undocumented I had to dig through wordpress source to figure it out. What I wrote up way back then:

One thing that was absolutely un-documented was a method to attach an image to a post. After some digging I found attach_uploads() which is a function that wordpress calls every time a post is created or edited over xml-rpc. What it does is search through the list of un-attached media objects and see if the new/edited post contains a link to them. Since I was trying to attach images so that the theme’s gallery would use them I didn’t necessarily want to link to the images within the post, nor did I want to edit wordpress. So what I ended up doing was including the image url within an html comment. -- danieru.com

Like I said messy but I searched high and low for a better method and I'm reasonably sure that none exists.

彼岸花似海 2024-12-14 11:59:51

从 Wordpress 3.5 开始,newmediaobject 现在可以半本地识别黑客攻击。

不再需要破解 class-wp-xmlrpc-server.php。

相反,您的 xml-rpc 客户端需要将帖子编号发送到名为 post_id 的变量。 (以前它只是变量“post”)

希望能帮助别人。

As of Wordpress 3.5, newmediaobject now recognizes the hack semi-natively.

it is no longer necessary to hack class-wp-xmlrpc-server.php.

Instead, your xml-rpc client needs to send the post number to a variable called post_id. (Previously it was just the variable 'post')

Hope that helps someone out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文