TranslateMenu.php
2.52 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace WPML\Core\Menu;
use WPML\LIB\WP\Hooks;
use WPML\LIB\WP\Post;
use function WPML\FP\spreadArgs;
class Translate implements \IWPML_Frontend_Action {
public function add_hooks() {
Hooks::onFilter( 'wp_get_nav_menu_items', 10, 2 )
->then( spreadArgs( [ self::class, 'translate' ] ) );
}
/**
* @param array $items An array of menu item post objects.
* @param \WP_Term $menu The menu object.
*
* @return array
*/
public static function translate( $items, $menu ) {
if ( self::doesNotHaveMenuInCurrentLanguage( $menu ) ) {
$items = wpml_collect( $items )
->filter( [ self::class, 'hasTranslation' ] )
->map( [ self::class, 'translateItem' ] )
->filter( [ self::class, 'canView' ] )
->values()
->toArray();
}
return $items;
}
/**
* @param \WP_Post $item Menu item - post object.
*
* @return bool
*/
public static function hasTranslation( $item ) {
global $sitepress;
return 'post_type' !== $item->type || (bool) self::getTranslatedId( $item ) || $sitepress->is_display_as_translated_post_type( $item->object );
}
/**
* @param \WP_Post $item Menu item - post object.
*
* @return \WP_Post
*/
public static function translateItem( $item ) {
if ( 'post_type' === $item->type ) {
$translatedId = self::getTranslatedId( $item, true );
$post = Post::get( $translatedId );
if ( ! $post instanceof \WP_Post ) {
return $item;
}
foreach ( get_object_vars( $post ) as $key => $value ) {
// We won't send the translated ID, since it affects front-end styles negatively.
if ( ! in_array( $key, [ 'menu_order', 'post_type', 'ID' ] ) ) {
$item->$key = $value;
}
}
$item->object_id = (string) $translatedId;
$item->title = $item->post_title;
}
return $item;
}
/**
* @param \WP_Post $item Menu item - post object.
*
* @return bool
*/
public static function canView( $item ) {
return current_user_can( 'administrator' ) || 'post_type' !== $item->type || 'draft' !== $item->post_status;
}
/**
* @param \WP_Term $menu The menu object.
*
* @return bool
*/
private static function doesNotHaveMenuInCurrentLanguage( $menu ) {
return ! wpml_object_id_filter( $menu->term_id, 'nav_menu' );
}
/**
* @param \WP_Post $item Menu item - post object.
* @param bool $return_original_if_missing
* @return int|null
*/
private static function getTranslatedId( $item, $return_original_if_missing = false ) {
return wpml_object_id_filter( $item->object_id, $item->object, $return_original_if_missing );
}
}