feat: add new methods for Attachment type

This commit is contained in:
Victor Westerlund 2026-02-22 10:53:56 +01:00
parent 1b0a9f385f
commit 7e873c48fa
Signed by: vlw
GPG key ID: D0AD730E1057DFC6

View file

@ -2,6 +2,9 @@
namespace vlw\WP\Posts\Type; namespace vlw\WP\Posts\Type;
use Exception;
use vlw\MimeTypes\MimeTypes;
use vlw\WP\Posts\Post; use vlw\WP\Posts\Post;
use vlw\WP\Posts\PostMeta; use vlw\WP\Posts\PostMeta;
use function vlw\WP\Support\slugify; use function vlw\WP\Support\slugify;
@ -13,8 +16,9 @@
class Attachment { class Attachment {
private const META_KEY_THUMBNAIL_ID = "_thumbnail_id"; private const META_KEY_THUMBNAIL_ID = "_thumbnail_id";
private const META_KEY_FEATURED_MEDIA = "_featured_media"; private const META_KEY_FEATURED_MEDIA = "_featured_media";
private const META_KEY_WP_ATTACHED_FILE = "_wp_attached_file";
private readonly Post $post; public private(set) readonly Post $post;
/** /**
* Return featured media for a Post if it exists * Return featured media for a Post if it exists
@ -73,6 +77,7 @@
$post->post_title = slugify($title); $post->post_title = slugify($title);
$post->guid = $url; $post->guid = $url;
$post->post_status = "inherit";
$post->post_type = "attachment"; $post->post_type = "attachment";
return new static($post->id); return new static($post->id);
@ -82,20 +87,33 @@
$this->post = new Post($id); $this->post = new Post($id);
} }
public string|false $content {
get => file_get_contents($this->post->guid);
}
public function set_attached_file(string $pathname): void {
PostMeta::new($this->post, self::META_KEY_WP_ATTACHED_FILE, $pathname);
}
public function set_from_file(string $file): void {
if (!is_file($file)) {
throw new Exception("No file found at location '{$file}'");
}
$this->post->post_mime_type = new MimeTypes()->get_type_from_file($file);
$this->set_attached_file($file);
}
/** /**
* Make this Attachment the featured media of a Post * Make this Attachment the featured media of a Post
* *
* @param Post $post * @param Post $post
* @return object * @return object
*/ */
public function set_post_featured(Post $post): object { public function set_post_featured(Post $post): void {
return (object) [ PostMeta::new($post, self::META_KEY_THUMBNAIL_ID, $this->id);
"thumbnail" => PostMeta::new($post, self::META_KEY_THUMBNAIL_ID, $this->id), PostMeta::new($post, self::META_KEY_FEATURED_MEDIA, "a:1:{i:0;s:3:\"{$this->id}\";}");
"featured_media" => PostMeta::new($post, self::META_KEY_FEATURED_MEDIA, "a:1:{i:0;s:3:\"{$this->id}\";}")
];
}
public string|false $content { $this->post->post_parent = $post;
get => file_get_contents($this->post->guid);
} }
} }