Есть вот такой код, который добавляет список постов HTML_Blocks, и по идее должен выводить выбранный пост в подменю элемента, в котором выбран пост. Но почему-то пост не выводится. Напишите пожалуйста, где я ошибся и где написанный код неверный и помогите решить проблему)
add_action( 'wp_nav_menu_item_custom_fields', 'add_menu_item_custom_fields', 10, 4 );
function add_menu_item_custom_fields( $item_id, $item, $depth, $args ) {
// Check if the menu item type is "post_type"
if ( 'post_type' !== $item->type ) {
return;
}
// Get the available posts in the post type
$posts = get_posts(
array(
'post_type' => 'HTML_Blocks',
'numberposts' => -1,
'post_status' => 'publish',
)
);
// If there are no available posts, do nothing
if ( empty( $posts ) ) {
return;
}
// Create the custom field for the list of posts
?>
<p class="field-custom description description-wide">
<label for="menu-item-post-<?php echo esc_attr( $item_id ); ?>-posts">
<?php esc_html_e( 'Select a post', 'text-domain' ); ?>
</label>
<select id="menu-item-post-<?php echo esc_attr( $item_id ); ?>-posts" class="widefat code edit-menu-item-custom" name="menu-item-post[<?php echo esc_attr( $item_id ); ?>][posts]">
<?php foreach ( $posts as $post ) : ?>
<option value="<?php echo esc_attr( $post->ID ); ?>" <?php selected( $post->ID, $item->object_id ); ?>>
<?php echo esc_html( $post->post_title ); ?>
</option>
<?php endforeach; ?>
</select>
</p>
<?php
}
add_filter( 'wp_nav_menu_objects', 'add_menu_item_post_content', 10, 2 );
function add_menu_item_post_content( $items, $args ) {
foreach ( $items as $item ) {
// Check if the menu item type is "post_type"
if ( 'post_type' !== $item->type ) {
continue;
}
// Get the selected post ID
$post_id = isset( $item->object_id ) ? intval( $item->object_id ) : 0;
// If the post ID is invalid, do nothing
if ( empty( $post_id ) ) {
continue;
}
// Get the selected post
$post = get_post( $post_id );
// If the post is invalid, do nothing
if ( empty( $post ) ) {
continue;
}
// Add the post content to the menu item
ob_start();
?>
<ul class="sub-menu">
<li class="menu-item">
<?php echo apply_filters( 'the_title', $post->post_title ); ?>
</li>
<li class="menu-item">
<?php echo apply_filters( 'the_content', $post->post_content ); ?>
</li>
</ul>
<?php
$item->classes[] = 'has-post-content';
$item->post_content = ob_get_clean();
}
return $items;
}