Home / eCommerce / Categorias pai a negrito e lembrete para nao esquecer de prencher certos campos ao adicionar um produto
Duplicate Snippet

Embed Snippet on Your Site

Categorias pai a negrito e lembrete para nao esquecer de prencher certos campos ao adicionar um produto

Code Preview
php
<?php
/**
 * Validação completa para produtos WooCommerce
 * Verifica preço, categoria, referência (SKU) e peso
 */
function validar_produto_woocommerce_completo($post_id) {
    // Verifica se é um produto
    if (get_post_type($post_id) !== 'product') {
        return;
    }
    
    // Verifica se está salvando o produto (não é um autosave)
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    // Verifica permissões do usuário
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // Busca o produto
    $product = wc_get_product($post_id);
    if (!$product) {
        return;
    }
    
    $errors = [];
    
    // 1. Verifica se o preço está vazio
    $regular_price = $product->get_regular_price();
    if (empty($regular_price)) {
        $errors[] = 'preço';
    }
    
    // 2. Verifica se possui categoria
    $product_cats = get_the_terms($post_id, 'product_cat');
    if (empty($product_cats) || is_wp_error($product_cats)) {
        $errors[] = 'categoria';
    }
    
    // 3. Verifica se possui SKU (referência)
    $sku = $product->get_sku();
    if (empty($sku)) {
        $errors[] = 'referência (SKU)';
    }
    
    // 4. Verifica se possui peso
    $weight = $product->get_weight();
    if (empty($weight)) {
        $errors[] = 'peso';
    }
    
    // Se houver erros, adiciona notificação
    if (!empty($errors)) {
        $error_message = '<strong>Atenção:</strong> O produto <a href="' . get_edit_post_link($post_id) . '">' . get_the_title($post_id) . '</a> está incompleto. ';
        $error_message .= 'Falta preencher: ' . implode(', ', $errors) . '.';
        
        WC_Admin_Notices::add_custom_notice(
            'produto_incompleto_' . $post_id,
            $error_message
        );
    } else {
        // Remove a notificação se todos os campos estiverem preenchidos
        WC_Admin_Notices::remove_notice('produto_incompleto_' . $post_id);
    }
}
add_action('save_post', 'validar_produto_woocommerce_completo', 20);
/**
 * Validação no lado do cliente (JavaScript) para impedir salvar produto incompleto
 */
function validar_produto_completo_js() {
    global $post_type;
    
    // Verifica se estamos na página de edição de produto
    if ($post_type !== 'product') {
        return;
    }
    
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        // Função para verificar os campos obrigatórios antes de publicar/atualizar
        function verificarProdutoAntesDePublicar() {
            var erros = [];
            
            // 1. Verificar preço
            var regularPrice = $('#_regular_price').val();
            if (!regularPrice || regularPrice === '') {
                erros.push('preço');
            }
            
            // 2. Verificar categoria
            // Verificamos se pelo menos uma categoria está marcada
            var temCategoria = false;
            $('#product_catchecklist input[type="checkbox"]').each(function() {
                if ($(this).is(':checked')) {
                    temCategoria = true;
                    return false; // Sai do loop se encontrar pelo menos uma categoria
                }
            });
            if (!temCategoria) {
                erros.push('categoria');
            }
            
            // 3. Verificar SKU (referência)
            var sku = $('#_sku').val();
            if (!sku || sku === '') {
                erros.push('referência (SKU)');
            }
            
            // 4. Verificar peso
            var weight = $('#_weight').val();
            if (!weight || weight === '') {
                erros.push('peso');
            }
            
            // Se houver erros, exibir alerta
            if (erros.length > 0) {
                alert('ATENÇÃO: O produto está incompleto. Faltam os seguintes campos obrigatórios: ' + erros.join(', ') + '.');
                return false;
            }
            
            return true;
        }
        
        // Interceptar o envio do formulário
        $('#post').on('submit', function(e) {
            // Se o botão clicado for "Publicar" ou "Atualizar"
            if ($('#publish').is(':focus') || $('#save-post').is(':focus')) {
                return verificarProdutoAntesDePublicar();
            }
        });
        
        // Adicionar verificação também ao clicar diretamente nos botões
        $('#publish, #save-post').on('click', function(e) {
            return verificarProdutoAntesDePublicar();
        });
    });
    </script>
    <?php
}
add_action('admin_footer', 'validar_produto_completo_js');
/**
 * Estilizar categorias pai em negrito
 */
function destacar_categorias_pai_produto() {
    global $post_type;
    
    // Aplica apenas na edição de produtos
    if ($post_type !== 'product') {
        return;
    }
    
    echo '<style>
        /* Aumentar o tamanho da caixa de categorias */
        .categorydiv div.tabs-panel,
        #taxonomy-product_cat .categorychecklist {
          max-height: 500px !important;
          height: auto !important;
          overflow: auto;
        }
        
        #product_catchecklist, 
        #product_catchecklist-pop, 
        #taxonomy-product_cat .categorychecklist {
          height: 500px !important;
          max-height: 500px !important;
        }
        
        .categorydiv .tabs-panel {
          min-height: 42px;
          height: 500px !important;
          overflow: auto;
          padding: 0 0.9em;
        }
        
        /* Deixar categorias pai em negrito */
        #product_catchecklist li.popular-category > label,
        #product_catchecklist > li > label,
        #product_cat-checklist li.popular-category > label,
        #product_cat-checklist > li > label {
          font-weight: bold !important;
        }
        
        /* Garantir que apenas categorias de primeiro nível (pai) fiquem em negrito */
        #product_catchecklist ul li > label,
        #product_cat-checklist ul li > label {
          font-weight: normal !important;
        }
        
        /* Estilo para destacar campos obrigatórios */
        ._regular_price_field label,
        ._sku_field label,
        ._weight_field label,
        #taxonomy-product_cat h2 {
            position: relative;
        }
        
        ._regular_price_field label:after,
        ._sku_field label:after,
        ._weight_field label:after,
        #taxonomy-product_cat h2:after {
            content: " *";
            color: red;
            font-weight: bold;
        }
    </style>';
    
    // JavaScript para destacar categorias pai
    echo '<script type="text/javascript">
        jQuery(document).ready(function($) {
            // Aplicar negrito às categorias pai
            function boldParentCategories() {
                $("#product_catchecklist > li > label, #product_cat-checklist > li > label").css("font-weight", "bold");
                $("#product_catchecklist ul li > label, #product_cat-checklist ul li > label").css("font-weight", "normal");
            }
            
            // Executar na inicialização
            boldParentCategories();
            
            // Executar quando categorias forem atualizadas/carregadas
            $(document).ajaxComplete(function() {
                setTimeout(boldParentCategories, 200);
            });
        });
    </script>';
}
add_action('admin_head-post.php', 'destacar_categorias_pai_produto');
add_action('admin_head-post-new.php', 'destacar_categorias_pai_produto');

Comments

Add a Comment