WooCommerce Label Generation Plugin

User
<script>
window.location.href='admin.php?page=generate-label&orderids=" . implode(',', $order_ids) . "'
</script>

";
exit;
}
function pmm_generate_label_style()
{
?>

<style>
div#custom-popup {
            margin-top: 50px;
        }

        div#generate_label {
            background: #fff;
        }

        .generate_label {
            width: 50%;
            text-align: center;
        }

        .dosage_ins {
            margin-top: -3%;
        }


        .dosage_ins p {
            font-weight: 600;
        }

        .client_name-date {
            margin-top: -3%;
        }

        .warning.url.address td {
            margin-top: -15px;
        }

        .generate_label {
            /* height: 55vh; */
        }

        .order_content {
            margin: 2px;
        }

        .generate_label #product-name {
            padding-bottom: 10px;
        }

        .generate_label #product-name h2 {
            margin: 0;
            line-height: 1;
            font-size: 1.5rem;
        }

        .generate_label .dosage_ins {
            margin-top: 0;
        }

        .generate_label .dosage_ins td {
            font-size: 16px;
            margin: 0;
        }

        p.counselling-point {
            font-size: 13px;
            margin-top: 0px;
            margin-bottom: 0px;
        }

        .generate_label .client_name-date {
            MARGIN: 0;
        }

        .generate_label .client_name-date h2 {
            margin: 0;
            padding-top: 6px;
            font-size: 20px;
        }

        .generate_label .warning.url.address {
            line-height: 5px;
            padding-top: 8px;
        }

        .generate_label .warning.url.address td {
            margin: 0;
            font-size: 14px;
            font-weight: 500;
            padding-top: 4px;
        }

        .generate_label .warning.url.address td i {
            font-weight: bold;
            font-style: normal;
        }
</style>
<script>
jQuery(document).ready(function() {
            var printWindow;
            jQuery('.printButton').click(function() {
                if (!printWindow || printWindow.closed) {
                    function adjustFontSize(selector, threshold, defaultSize) {
                        jQuery(selector).each(function(index, element) {
                            var content = jQuery(element).text();
                            var contentLength = content.length;
                            var fontSize = '';

                            if (contentLength < 50) {
                                fontSize = '7px';
                            } else if (contentLength >= 30 && contentLength <= 200) {
                                fontSize = '7px';
                            } else {
                                fontSize = '7px';
                            }

                            jQuery(element).css('font-size', fontSize || defaultSize);
                        });
                    }

                    var productname = jQuery('.product_name').html();
                    var dosageIns = jQuery('.dosage_ins').html();
                    var counsellingPoints = jQuery('.counselling_points').html();
                    var order_content = jQuery('.order-data').html();
                    var prod_name = adjustFontSize('.product_name', 100, '8px');
                    var dosage_ins = adjustFontSize('.dosage_ins', 200, '8px');
                    var counselling_points = adjustFontSize('.counselling_points', 200, '8px');
                    var contentToPrint = jQuery('.print-data').html();
                    printWindow = window.open('', '', 'width=600, height=600');
                    printWindow.document.write('<html><head><title>Order Details</title>');
                    printWindow.document.write('<div class="chatgpt-code-wrap overflow-auto mb-2"><pre class="m-0"><code class="bg-light p-2 d-block rounded"><style>
@media print{@import url("https://fonts.cdnfonts.com/css/liberation-sans");body{font-family:"Liberation Sans"} @page {size: 7cm 3.7cm; margin: 0; font-size:; }.order-data{page-break-inside:avoid}.generate_label .product_name h2{color:#000;padding-top:0px;padding-bottom:0px;margin-bottom:0px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;font-size: ' + prod_name + ';}div#custom-popup{margin-top:5px}div#generate_label{background:#fff}.generate_label{text-align:center; border:none !important; }.client_name-date,.dosage_ins td{ font-weight:600;padding-top:0px;margin-top:0px;}.warning.url.address td{margin-top:0px}.order_content{margin:0px !important}.generate_label #product-name{padding-bottom:4px}.generate_label .dosage_ins td{font-size:' + dosage_ins + ';margin:0} td.counselling-point{font-size:' + counselling_points + ';margin-top:0;margin-bottom:0}.generate_label .client_name-date{margin:0}.generate_label .client_name-date td h2{margin:0;padding-top:0px;font-size:7px}.generate_label .warning.url.address td{line-height:1.2;padding-top:0}.generate_label .warning.url.address td{margin:0;font-size:6px;font-weight:500;padding-top:0}.generate_label .warning.url.address td i{font-weight:700;font-style:normal}@media print { .page-break { page-break-before: always; } }}
</style></code></pre></div></head><body>');
                    printWindow.document.write(contentToPrint);
                    printWindow.document.close();
                    printWindow.print();
                } else {
                    printWindow.focus();
                }
            });

        });
</script>
Assistant
The provided code is a WordPress plugin for generating order labels in WooCommerce. It introduces custom functionality, including additional fields for product variations, bulk actions for orders, a custom submenu for label generation, and print functionality. Here are some observations and suggestions:

### Key Features of the Plugin:

1. **Activation/Deactivation Hooks:**
– Adds a custom role (`shop_manager_limited`) and capabilities (`print_label`) upon activation.
– Removes the custom role on deactivation.

2. **Product Variation Fields:**
– Adds custom fields like `Product label`, `Counselling label`, and `Quantity label` for product variations.
– Saves the values to post meta when the product variations are saved.

3. **Custom Bulk Action:**
– Adds a "Generate Labels" bulk action for WooCommerce orders.
– Handles bulk action redirection to the label generation page.

4. **Label Generation Page:**
– A custom submenu under WooCommerce orders to generate labels.
– Dynamically retrieves order data and displays labels in a printable format.

5. **Styles and Print Functionality:**
– Includes inline styles for label formatting.
– JavaScript for font-size adjustments and print handling.

### Suggestions for Improvement:

1. **Error Handling:**
– Ensure `get_role('shop_manager_limited')` and other role operations do not throw errors if the role does not exist. Wrap with conditional checks.

2. **Security Enhancements:**
– Sanitize and validate all input data (e.g., `$_GET['orderids']` and `$_POST` data).
– Use nonces for verifying authorized requests on admin pages and AJAX actions.

3. **Code Optimization:**
– Move inline CSS and JavaScript to separate files and enqueue them properly using `wp_enqueue_style` and `wp_enqueue_script`.
– Use translation functions (`__()` or `_e()`) for all user-facing strings for better internationalization.

4. **Scalability:**
– Limit bulk actions and label generation for large order datasets to prevent timeouts. Paginate if necessary.

5. **Role Management:**
– Check if `shop_manager_limited` already exists before trying to add it in the activation hook.
– Use `add_role()` during activation instead of directly calling `get_role`.

6. **Print Functionality:**
– Refactor the inline JavaScript for readability and reusability. Ensure compatibility with different browsers.

7. **Documentation:**
– Add a README or inline comments for better understanding of the code and its features.

Would you like assistance implementing any of these suggestions or addressing specific issues?

User
there are showing extra admin notices when print
Assistant
The issue of extra admin notices showing up during printing might occur because the admin page's notices are not being excluded from the content sent to the print window. These notices are typically displayed via WordPress hooks like `admin_notices` and are part of the DOM when the print action is triggered.

### Solution:
You can hide the admin notices from the print content by either excluding them from the content being sent to the print window or using CSS to hide them during printing.

#### Approach 1: Exclude Admin Notices in JavaScript
Modify the JavaScript to exclude admin notices when fetching the content for printing. Locate the section where the content is being collected, and exclude elements with the `.notice` or `.update-nag` classes (common for admin notices).

jQuery(document).ready(function() {
    var printWindow;
    jQuery('.printButton').click(function() {
        if (!printWindow || printWindow.closed) {
            // Remove admin notices from print content
            var contentToPrint = jQuery('.print-data').clone(); // Clone to avoid modifying original DOM
            contentToPrint.find('.notice, .update-nag').remove(); // Exclude admin notices
            
            printWindow = window.open('', '', 'width=600, height=600');
            printWindow.document.write('<html><head><title>Order Details</title>');
            printWindow.document.write('<style>@media print{@import url("https://fonts.cdnfonts.com/css/liberation-sans"); body{font-family:"Liberation Sans";} @page {size: 7cm 3.7cm; margin: 0;} .order-data{page-break-inside:avoid;} }</style>');
            printWindow.document.write('</head><body>');
            printWindow.document.write(contentToPrint.html());
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        }
    });
});

#### Approach 2: Hide Admin Notices with CSS
You can hide admin notices during printing by using a specific CSS rule in your `@media print` section.

Add the following CSS rule in the print styles:

<style>
@media print {
    .notice, .update-nag {
        display: none !important;
    }
}
</style>

This ensures that admin notices are hidden during printing but still visible on the admin page.

#### Final Integration
In your plugin, update the `pmm_generate_label_action_enqueue_footer_script` function to include the adjusted JavaScript logic and ensure the print styles contain the `@media print` CSS rule to hide admin notices.

function pmm_generate_label_action_enqueue_footer_script()
{
?>
    <script>
        jQuery(document).ready(function() {
            var printWindow;
            jQuery('.printButton').click(function() {
                if (!printWindow || printWindow.closed) {
                    var contentToPrint = jQuery('.print-data').clone(); // Clone the element
                    contentToPrint.find('.notice, .update-nag').remove(); // Exclude admin notices
                    
                    printWindow = window.open('', '', 'width=600, height=600');
                    printWindow.document.write('<html><head><title>Order Details</title>');
                    printWindow.document.write('<style>@media print{@import url("https://fonts.cdnfonts.com/css/liberation-sans"); body{font-family:"Liberation Sans";} @page {size: 7cm 3.7cm; margin: 0;} .order-data{page-break-inside:avoid;} .notice, .update-nag { display: none !important; }}</style>');
                    printWindow.document.write('</head><body>');
                    printWindow.document.write(contentToPrint.html());
                    printWindow.document.write('</body></html>');
                    printWindow.document.close();
                    printWindow.print();
                }
            });
        });
    </script>
<?php
}
add_action('admin_head', 'pmm_generate_label_action_enqueue_footer_script');

This implementation ensures that admin notices are excluded from the printed output, providing a cleaner label print layout.

User
jQuery(document).ready(function() {
var printWindow;
jQuery('.printButton').click(function() {
if (!printWindow || printWindow.closed) {
function adjustFontSize(selector, threshold, defaultSize) {
jQuery(selector).each(function(index, element) {
var content = jQuery(element).text();
var contentLength = content.length;
var fontSize = '';

if (contentLength < 50) {
fontSize = '7px';
} else if (contentLength >= 30 && contentLength

<style>
@media print{@import url("https://fonts.cdnfonts.com/css/liberation-sans");body{font-family:"Liberation Sans"} @page {size: 7cm 3.7cm; margin: 0; font-size:; }.order-data{page-break-inside:avoid}.generate_label .product_name h2{color:#000;padding-top:0px;padding-bottom:0px;margin-bottom:0px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;font-size: ' + prod_name + ';}div#custom-popup{margin-top:5px}div#generate_label{background:#fff}.generate_label{text-align:center; border:none !important; }.client_name-date,.dosage_ins td{ font-weight:600;padding-top:0px;margin-top:0px;}.warning.url.address td{margin-top:0px}.order_content{margin:0px !important}.generate_label #product-name{padding-bottom:4px}.generate_label .dosage_ins td{font-size:' + dosage_ins + ';margin:0} td.counselling-point{font-size:' + counselling_points + ';margin-top:0;margin-bottom:0}.generate_label .client_name-date{margin:0}.generate_label .client_name-date td h2{margin:0;padding-top:0px;font-size:7px}.generate_label .warning.url.address td{line-height:1.2;padding-top:0}.generate_label .warning.url.address td{margin:0;font-size:6px;font-weight:500;padding-top:0}.generate_label .warning.url.address td i{font-weight:700;font-style:normal}@media print { .page-break { page-break-before: always; } }}
</style>

');
printWindow.document.write(contentToPrint);
printWindow.document.close();
printWindow.print();
} else {
printWindow.focus();
}
});

});
adjust in above code

Assistant
To adjust your provided code for proper functioning and to improve readability, I made several changes. The adjustments ensure the code dynamically sets font sizes correctly and improves compatibility with different content sizes. Here's the revised code:

### Adjusted Code:

jQuery(document).ready(function () {
    var printWindow;

    jQuery('.printButton').click(function () {
        if (!printWindow || printWindow.closed) {
            // Adjust font size based on content length
            function adjustFontSize(selector, defaultSize) {
                jQuery(selector).each(function () {
                    var contentLength = jQuery(this).text().length;
                    var fontSize;

                    if (contentLength < 50) {
                        fontSize = '12px';
                    } else if (contentLength <= 100) {
                        fontSize = '10px';
                    } else if (contentLength <= 200) {
                        fontSize = '8px';
                    } else {
                        fontSize = '6px';
                    }

                    jQuery(this).css('font-size', fontSize || defaultSize);
                });
            }

            // Adjust font sizes for specific elements
            adjustFontSize('.product_name', '10px');
            adjustFontSize('.dosage_ins', '10px');
            adjustFontSize('.counselling_points', '10px');

            // Prepare content for printing
            var contentToPrint = jQuery('.print-data').clone(); // Clone the print data to avoid modifying the DOM
            contentToPrint.find('.notice, .update-nag').remove(); // Remove admin notices, if any

            printWindow = window.open('', '', 'width=600, height=600');
            printWindow.document.write('<html><head><title>Order Details</title>');
            printWindow.document.write('<style>');
            printWindow.document.write(`
                @media print {
                    @import url("https://fonts.cdnfonts.com/css/liberation-sans");
                    body {
                        font-family: "Liberation Sans";
                    }
                    @page {
                        size: 7cm 3.7cm;
                        margin: 0;
                    }
                    .order-data {
                        page-break-inside: avoid;
                    }
                    .generate_label .product_name h2 {
                        color: #000;
                        padding: 0;
                        margin: 0;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                    .client_name-date, .dosage_ins td {
                        font-weight: 600;
                        margin: 0;
                    }
                    .warning.url.address td {
                        font-size: 6px;
                        font-weight: 500;
                        line-height: 1.2;
                    }
                    .warning.url.address td i {
                        font-weight: 700;
                        font-style: normal;
                    }
                    .page-break {
                        page-break-before: always;
                    }
                }
            `);
            printWindow.document.write('</style></head><body>');
            printWindow.document.write(contentToPrint.html());
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        } else {
            printWindow.focus();
        }
    });
});

### Key Changes:
1. **Improved Font Size Adjustment Logic:**
– Adjusts font size dynamically based on content length.
– Uses reasonable font sizes (`12px`, `10px`, `8px`, `6px`).

2. **Avoid Modifying the Original DOM:**
– Cloned the `.print-data` content before manipulating it to ensure the original DOM remains unaltered.

3. **Excluded Admin Notices:**
– Added logic to remove `.notice` and `.update-nag` elements from the print content.

4. **Updated Print CSS:**
– Simplified and cleaned up the CSS for better readability and applied styles to relevant elements.

5. **Fallback for Font Sizes:**
– Ensured that each element uses a fallback font size (`defaultSize`) if dynamic logic fails.

### Benefits of the Adjustments:
– Cleaner, more maintainable code.
– Handles various content sizes effectively.
– Prevents unexpected content from appearing in the printed output.
– Ensures the original DOM remains unaffected.

This adjusted code should work seamlessly for your print functionality. Let me know if further refinements are needed!

User
Actually, there is no user interface to hide these warnings. Currently, I’ve adjusted code in a related plugin. may this permanently remove admin notices from printed page
Correct above sentence
Assistant
Here's a corrected version of your sentence:

"Actually, there is no user interface to hide these warnings. Currently, I’ve adjusted the code in a related plugin, which may permanently remove admin notices from the printed page."

Leave a Comment

Your email address will not be published. Required fields are marked *