У кого-либо есть идея о том, как позволить пользователю заглядывать разделителям или делителям между определенными военно-морскими пунктами меню?
Google только, кажется, воспитывает новобранца подсказки CSS для первых/последних дочерних селекторов, но я после чего-то очень как закладки Firefox.
ОБНОВЛЕНИЕ:
Я действительно ценю весь вход до сих пор, но я уточню для предотвращения дальнейшего беспорядка;
wp_nav_menu
Обычно я пахал бы в и просто взялся бы за работу. Но так как это - только возможное требование для предстоящего проекта, я думал, что уже буду видеть если чей-либо испытанный что-то подобное.
Плюс я думал, что это могло бы на самом деле быть полезно для других и отправит мою собственную обратную связь/результаты, если я возобновляю его.
Используйте пользовательского Уокера. Расшириться start_el()
распечатать <li class="menu_separator"><hr></li>
если заголовок меню просто a '-'
.
function wpse38241_setup_menu()
{
register_nav_menu( 'main-menu', 'Main Menu' );
}
add_action( 'after_setup_theme', 'wpse38241_setup_menu' );
/**
* Replaces items with '-' as title with li class="menu_separator"
*
* @author Thomas Scholz (toscho)
*/
class Wpse38241_Separator_Walker extends Walker_Nav_Menu
{
/**
* Start the element output.
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. May be used for padding.
* @param array $args Additional strings.
* @return void
*/
public function start_el( &$output, $item, $depth, $args )
{
if ( '-' === $item->title )
{
// you may remove the <hr> here and use plain CSS.
$output .= '<li class="menu_separator"><hr>';
}
else
{
parent::start_el( &$output, $item, $depth, $args );
}
}
}
Теперь создайте свое обычное меню. Добавьте объект с '-'
как заголовок:
wp_nav_menu(
array (
'menu' => 'main-menu',
'container' => FALSE,
'container_id' => FALSE,
'menu_class' => '',
'menu_id' => FALSE,
'walker' => new Wpse38241_Separator_Walker
)
);
(переформатированный для удобочитаемости)
<ul id="menu-separated" class="">
<li id="menu-item-92" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-92">
<a href="https://wordpress.stackexchange.com/questions/38241/nav-menu-separators">Nav menu separators?</a>
</li>
<li class="menu_separator">
<hr>
</li>
<li id="menu-item-93" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-93">
<a href="https://wordpress.stackexchange.com/">wordpress.stackexchange.com</a>
</li>
</ul>
Это работает даже без JavaScript и CSS.
Вы собираетесь, должны иметь 2 уровня к этому, Сценарий PHP, чтобы сохранить предпочтение пользователя и воссоздать его после возвращения и сценария JS, чтобы позволить им помещать его. Как Вы обрабатываете размещение Вам решать, я, вероятно, пошел бы с интерфейсом перетаскивания. Мой сценарий пошел бы что-то как следующее:
add_action( 'wp_enqueue_scripts', 'my_divider_enqueue' );
add_action( 'wp_ajax_insert-divider', 'ajax_insert_divider' );
// enqueue the script
function my_divider_enqueue() {
// register the script elsewhere, preferably in an init hook
wp_enqueue_script( 'divider-js' );
$passed_vars = array(
'ajaxurl' => admin_url('admin-ajax.php' ),
'nonce' => wp_create_nonce( 'divider-ajax-nonce' )
);
if( is_user_logged_in() )
$passed_vars['prev'] => get_user_meta( $current_user->ID, 'divider_location', true ); // you shouldn't need to declare $current_user, but you may
wp_localize_script( 'divider-js', 'divider', $passed_vars );
}
// handle the js
function ajax_insert_divider() {
if( !wp_verify_nonce( $_POST['divider_nonce'], 'divider-ajax-nonce' ) ) {
header("HTTP/1.0 401 Internal Server Error", true, 401);
exit;
} else {
//may not be necessary, you can test this
global $current_user;
get_currentuserinfo();
//update user meta
update_user_meta( $current_user->ID, 'divider_location', $_POST['divider_location'] );
}
exit;
}
Документы: wp_register_script()
, wp_enqueue_script()
, wp_localize_script()
, wp_create_nonce()
, is_user_logged_in()
, get_user_meta()
, wp_verify_nonce()
, get_currentuserinfo()
, update_user_meta()
и затем после этого имейте некоторый javascript/jQuery для обработки, когда пользователь изменяется (это - псевдокод, так как реализация - что-то, что необходимо будет выбрать),
jQuery(document).ready(function(){
//when the user releases the divider in the desired location, do some stuff
jQuery('.divider').mouseup(function() {
if( divider_is_valid() ) {
place_divider();
} else {
reset_divider();
}
});
//using divider.prev, place the desired dividers
});
function reset_divider() {
//put the divider back where it started, either in a holder for unused dividers or where it was in the menu previously
}
function place_divider() {
//place divider where it's going
jQuery.post(
divider.ajaxurl,
{
action : 'insert-divider',
divider_nonce : divider.nonce,
location : //some representation of the location that you can call later
},
function( response ) {
//execute any actions you need to do on response
}
);
}
Сценарий полностью не тестируется (я записал это непосредственно в редактора ответа lol), но это должно получить Вас идущий в правильном направлении.