Attachments.php
1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
namespace ACP\Editing\Storage\Post;
use AC\Storage\Transaction;
class Attachments extends Field {
public function __construct() {
parent::__construct( 'post_parent' );
}
public function get( $id ) {
$attachment_ids = get_posts( [
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => null,
'post_parent' => $id,
'fields' => 'ids',
] );
if ( ! $attachment_ids ) {
return [];
}
return $attachment_ids;
}
public function update( $id, $attachment_ids ) {
$current_attachment_ids = get_posts( [
'post_type' => 'attachment',
'post_parent' => $id,
'posts_per_page' => -1,
'fields' => 'ids',
] );
$transaction = new Transaction();
$results = [];
// Detach
if ( $current_attachment_ids ) {
foreach ( $current_attachment_ids as $attachment_id ) {
$results[] = parent::update( $attachment_id, '' );
}
}
// Attach
if ( ! empty( $attachment_ids ) ) {
foreach ( $attachment_ids as $attachment_id ) {
$results[] = parent::update( $attachment_id, $id );
}
}
if ( in_array( false, $results, true ) ) {
$transaction->rollback();
return false;
}
$transaction->commit();
return true;
}
}