BlockTemplates.php
2.16 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
67
68
69
70
71
72
73
74
75
76
77
<?php
namespace WPML\FullSiteEditing;
use WPML\Element\API\PostTranslations;
use WPML\FP\Lst;
use WPML\FP\Obj;
use WPML\LIB\WP\Hooks;
use WPML\LIB\WP\Post;
use function WPML\FP\spreadArgs;
class BlockTemplates implements \IWPML_Backend_Action, \IWPML_Frontend_Action, \IWPML_REST_Action {
public function add_hooks() {
Hooks::onFilter( 'wpml_tm_translation_job_data', 10, 2 )
->then( spreadArgs( [ self::class, 'doNotTranslateTitle' ] ) );
Hooks::onFilter( 'wpml_pre_save_pro_translation', 10, 2 )
->then( spreadArgs( [ self::class, 'copyOriginalTitleToTranslation' ] ) );
Hooks::onAction( "rest_after_insert_wp_template", 10, 1 )
->then( spreadArgs( [ self::class, 'syncPostName' ] ) );
Hooks::onAction( "rest_after_insert_wp_template_part", 10, 1 )
->then( spreadArgs( [ self::class, 'syncPostName' ] ) );
}
/**
* @param array $package
* @param object $post
*
* @return array
*/
public static function doNotTranslateTitle( array $package, $post ) {
if ( Lst::includes( Obj::prop( 'post_type', $post ), [ 'wp_template', 'wp_template_part' ] ) ) {
$package = Obj::assocPath( [ 'contents', 'title', 'translate' ], 0, $package );
}
return $package;
}
/**
* @param array $postData
* @param object $job
*
* @return array
*/
public static function copyOriginalTitleToTranslation( $postData, $job ) {
if ( Lst::includes(
Obj::prop( 'original_post_type', $job ),
[ 'post_wp_template', 'post_wp_template_part' ]
) ) {
// WordPress looks up the post by 'name' so we need the translation to have the same name.
$post = Post::get( $job->original_doc_id );
$postData['post_title'] = $post->post_title;
$postData['post_name'] = $post->post_name;
}
return $postData;
}
/**
* @param \WP_Post $post Inserted or updated post object.
*/
public static function syncPostName( \WP_Post $post ) {
wpml_collect( PostTranslations::get( $post->ID ) )
->reject( Obj::prop( 'original' ) )
->pluck( 'element_id' )
->map( function ( $postId ) use ( $post ) {
global $wpdb;
$wpdb->update( $wpdb->prefix . 'posts', [ 'post_name' => $post->post_name ], [ 'ID' => $postId ] );
} );
}
}