codememo

XMLRPC를 이용하여 워드프레스에 사진이 첨부된 새로운 게시물을 만드는 방법은?

tipmemo 2023. 10. 30. 21:02
반응형

XMLRPC를 이용하여 워드프레스에 사진이 첨부된 새로운 게시물을 만드는 방법은?

XMLRPC를 사용하여 워드프레스에 사진이 첨부된 새로운 게시물을 만드는 방법을 아는 사람?

새 게시물을 생성하고 새 사진을 따로 업로드 할 수 있는데, 생성된 게시물에 업로드된 사진을 첨부할 방법이 없는 것 같습니까?

아래는 제가 현재 사용하고 있는 코드입니다.

<?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 )
}
?>

저는 WordPress 사이트(현재 고용주는 이 중 3개를 사용함)에 참여하여 매일 게시하고 있으며 대량으로 제가 가장 잘하는 스크립트를 사용하도록 강요했습니다.

PHP 기반이며 사용 및 배포가 쉽고 빠릅니다.보안은?.htaccess를 사용하여 보안을 유지합니다.

연구에 따르면 파일에 관한 XMLRPC는 워드프레스가 정말 싫어하는 것 중 하나입니다.일단 파일을 업로드하면 해당 첨부 파일을 특정 게시물에 연결할 수 없습니다!그러니까요, 짜증나요.

그래서 스스로 해결해 보기로 했습니다.그 일을 해결하는 데 일주일이 걸렸습니다.XMLRPC를 준수하는 퍼블리싱 클라이언트를 100% 제어해야 합니다. 그렇지 않으면 아무런 의미가 없습니다.

WordPress 설치 시 다음이 필요합니다.

  • class-IXR.php, /wp-admin/포함 위치
  • class-wp-xmlrpc-server.php, /wp-에 위치합니다.

저처럼 직접 포스팅 도구를 만드시면 class-IXR.php가 필요합니다.그들은 올바르게 작동하는 base64 인코더를 가지고 있습니다.PHP와 함께 제공되는 것을 믿지 마십시오.

또한 프로그래밍에 어느 정도 경험이 있어야 이를 이해할 수 있습니다.좀 더 명확해지도록 노력하겠습니다.

  1. class-wp-xmlrpc-server.php 수정

    • ftp를 통해 컴퓨터에 다운로드합니다.만일의 경우를 대비해 복사본을 백업합니다.
    • 텍스트 편집기에서 파일을 엽니다.포맷되지 않은 경우(일반적으로 사용 중인 유닉스 타입 캐리지 브레이크) 다른 곳에서 열거나 울트라 에디트 같은 것을 사용합니다.
    • 주의를 기울입니다.mw_newMediaObject기능. 우리의 목표입니다.이게 우리의 목표입니다.여기 약간의 메모; 워드프레스는 블로거와 이동형으로부터 기능을 빌려왔습니다.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']; //the post ID to attach to.
       $type = $data['type'];
       $bits = $data['bits'];
      

      새로운 $post 변수를 기록합니다.새 파일 업로드 요청을 할 때마다 'post' 인수를 첨부할 수 있습니다.

      우편 번호를 찾는 방법은 xmlrpc 호환 클라이언트로 게시물을 추가하는 방법에 따라 달라집니다.일반적으로 게시물을 통해 이 내용을 확인해야 합니다.숫자 값입니다.

      위의 내용을 편집했으면 이제 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' ]
      );
      
    • 그래서 어떤 게시물에도 이미지가 연결되지 않는 이유가 여기에 있습니다!post_parent 인수의 기본값은 항상 0입니다!이제는 그럴 일이 없을 겁니다

      // 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가 xmlrpc 요청에서 오는 $post 값을 사용합니다.일단 이것이 첨부 파일에 커밋되면, 당신이 원하는 모든 게시물과 연결될 것입니다!

      이것은 개선될 수 있습니다.값을 입력하지 않아도 깨지지 않도록 기본값을 지정할 수 있습니다.비록 내 쪽에 있지만, 나는 클라이언트에 기본값을 붙였고, 나 말고는 아무도 XMLRPC 인터페이스에 접속하지 않습니다.

    • 변경을 완료한 후 파일을 저장하고 찾은 경로에 파일을 다시 업로드합니다.다시 한 번 백업을 해야 합니다.

      이 모듈에 영향을 미치는 WordPress 업데이트를 주의해야 합니다.그런 경우 이 편집을 다시 적용해야 합니다!

  2. PHP 유형 편집기에 class-IXR.php를 포함합니다.다른 걸 쓰시는 거라면 제가 도와드릴 수가 없네요. :(

이것이 몇몇 사람들에게 도움이 되길 바랍니다.

게시물을 올리면 워드프레스에서 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
        )
    );
}

메소드 호출 후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' ) );

해결 방법은 다음과 같은 인수를 사용하여 호출하는 방법입니다.

$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();
}

PHP 테스트를 위해 Incutio XML-RPC Library를 사용했고 나머지 코드는 정확히 질문과 같습니다.

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 );  
}
?>

저는 몇 달 전에 이것을 해야 했습니다.그것은 가능할 뿐만 아니라 문서화되지 않은 것일 뿐만 아니라 나는 그것을 알아내기 위해 워드프레스 소스를 파헤쳐야 했습니다.그때 내가 작성한 것은:

전혀 문서화되지 않은 한 가지는 게시물에 이미지를 첨부하는 방법이었습니다.약간의 탐색 끝에 xml-rpc를 통해 게시물이 생성되거나 편집될 때마다 워드프레스로 호출하는 함수인 attach_uploads()를 발견했습니다.첨부되지 않은 미디어 개체 목록을 검색하여 새/편집된 게시물에 해당 개체에 대한 링크가 포함되어 있는지 확인합니다.테마의 갤러리에서 사용할 수 있도록 이미지를 첨부하려고 했기 때문에 반드시 게시물 내의 이미지에 링크하고 싶지도 않았고 워드프레스를 편집하고 싶지도 않았습니다.그래서 저는 html 주석에 url 이미지를 포함시켰습니다. -- danieru.com

지저분하다고 말했지만 나는 더 나은 방법을 찾기 위해 높은 곳에서 낮은 곳을 찾았고 나는 존재하지 않는다고 합리적으로 확신합니다.

워드프레스 3.5 현재 뉴미디어 오브젝트는 반토종적으로 해킹을 인식하고 있습니다.

더 이상 class-wp-xmlrpc-server.php를 해킹할 필요가 없습니다.

대신 xml-rpc 클라이언트는 포스트 번호를 post_id라는 변수로 보내야 합니다. (이전에는 그냥 'post'라는 변수였습니다.)

누군가에게 도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/7607473/how-to-create-new-post-with-photo-attached-in-wordpress-using-xmlrpc

반응형