在创建页面上自动设置页面顺序

时间:2014-07-27 作者:Giraldi

有没有办法automatically set page order 至最后订单号upon creating new pages 而不是将其设置为0?

2 个回复
最合适的回答,由SO网友:bonger 整理而成

您可以使用ajax和admin_footer-post-new.php 钩根据您想要的是最高的订单号还是最近发布的订单号,sql会有所不同。以下返回最高发布订单号+1:

function wpse155926_set_menu_order() {
    $ret = array();

    if ( check_ajax_referer( \'wpse155926_set_menu_order_post\', \'nonce\', false /*die*/ ) ) {
        global $wpdb;
        //last published
        //$sql = $wpdb->prepare( \'SELECT menu_order FROM \' . $wpdb->posts . \' WHERE post_type = %s AND post_status = %s ORDER BY post_date DESC LIMIT 1\', \'page\', \'publish\' );
        //highest published
        $sql = $wpdb->prepare( \'SELECT menu_order FROM \' . $wpdb->posts . \' WHERE post_type = %s AND post_status = %s ORDER BY menu_order DESC LIMIT 1\', \'page\', \'publish\' );
        if ( ( $result = $wpdb->get_var( $sql ) ) !== false ) {
            $ret[\'menu_order\'] = $result + 1;
        }
    }

    header(\'Content-type: application/json\');
    die( json_encode( $ret ) );
}
add_action( \'wp_ajax_wpse155926_set_menu_order\', \'wpse155926_set_menu_order\' );

function wpse155926_admin_footer_post_new_php() {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
    (function ($) {
        $.post( ajaxurl, {
                action: \'wpse155926_set_menu_order\',
                nonce: <?php echo json_encode( wp_create_nonce( \'wpse155926_set_menu_order_post\' ) ); ?>
            }, function(response) {
                if (response && response.menu_order) {
                    $(\'#pageparentdiv input[name="menu_order"]\').val(response.menu_order);
                }
            }, \'json\'
        );
    })(jQuery);
});
</script>
<?php
}
add_action( \'admin_footer-post-new.php\', \'wpse155926_admin_footer_post_new_php\' );

SO网友:karpstrucking

你可以钓到publish_page 过渡状态操作并使用简单的SQL查询(通过$wpdb) 确定的最大电流值menu_order{prefix}_posts 表并设置menu_order 相应的新页面。示例代码:

add_action( \'publish_page\', \'wpse155926_set_to_last_page\', 10, 2 );
function wpse155926_set_to_last_page( $ID, $post ) {
  if ( $post->menu_order === 0 ) {
    global $wpdb;
    $query = "SELECT MAX(menu_order) FROM $wpdb->posts WHERE post_type LIKE \'page\' AND post_status LIKE \'publish\';";
    $max_menu_order = $wpdb->get_var( $query );
    $post->menu_order = ++$max_menu_order;
    remove_action(\'publish_page\', \'wpse155926_set_to_last_page\');
    wp_update_post( $post );
    add_action(\'publish_page\', \'wpse155926_set_to_last_page\');
  }
}

结束

相关推荐

Static pages not working

我已经成功地在我正在构建的主题上使用了一个静态首页(本地因此无法共享URL),没有任何问题。突然,它停止了工作,我不知道为什么。我现在看到的是一个空白页面,而不是我的博客类别帖子。我在工作和休息之间做的最后一个改变是添加了<?php else: ?> 语句输入到我的索引中。php以及&! is_front_page() 输入if语句,以便在静态主页上显示不同的内容。指数php:<?php get_header(); ?> <div id=\"content\"