Marcus
Forum Replies Created
-
Please add this meta to your XSL in next Update)
Example:
<title>XML Sitemap</title>
<meta name="description" content="This file was dynamically generated using the WordPress content management system and XML Sitemap Generator for Google by Auctollo.">PS. You can replace add_action(‘template_redirect’ to add_action(‘init’ if will not work
Question: Can you go into a little more detail on WHERE that hook should be added? I have a medium understanding of the backend of WordPress/Woo but am I adding that function to a specific template? Which one? is template_redirect one of the theme files? Probably one I need to add?
So you must add code to functions.php (Your Active Theme) At the beginning of the file or at the end, as you like. template_redirect – Hook this WordPress Hook..
Add the code to the theme and then just try to go to https://yourdomain.com/checkout/?add-to-cart=gla_here_productID if code work you should get a link https://yourdomain.com/checkout/?add-to-cart=here_productID
note that in the condition of the code, you can replace the prefix gla_ with whatever you use
- This reply was modified 1 year, 11 months ago by Marcus.
From my perspective, it’s time for developers to add a new option in the settings that allows choosing a custom prefix, such as
example_*, and also the ability to disable it altogether. If no rules are applied, simply usegla_as the default. This way, people won’t have to look for solutions to such problems, as I have faced. Why is this necessary ifgla_is not supported when forming the checkout link? It’s ridiculous… Developers of WooCommerce should then add support so thatgla_productIDis supported inhttps://site.com/checkout/?add-to-cart={id}.”Hi.
- Remove all items for you sync before
- Add this code to functions.php The gla_ prefix is automatically added to products to help identify products synced by the Google for WooCommerce extension. If you’d like to remove the prefix, please use this code snippet:
// Sync products without GLA prefix.
add_action(
'woocommerce_gla_get_google_product_offer_id',
function ( $mc_id, $product_id ) {
return (string) $product_id;
},
10,
2
);Please note:
- This would cause all the products to be added again, as a different ID means a new product.
- Historic reports for campaigns that used the gla_ prefix would no longer match.
- To avoid having duplicate products, please remove all existing products in Google Merchant Center by following these steps:
- Go to the test connection page: example.com/wp-admin/admin.php?page=connection-test-admin-page (replace example.com with your domain name)
- Scroll to the bottom of the page, Under “Product Sync” click Delete All Synced Products from Google Merchant Center and allow a few minutes for all existing products to be removed from GMC. This will ensure that products synced afterwards don’t have the gla_ prefix.
Solution 2: (This method allows you not to re-upload products again, but there is a caveat that this puts additional load on the server. However, it preserves the existing analytics with the
gla_prefix.)add_action('template_redirect', 'gla_remove_prefix_from_cart_url'); function gla_remove_prefix_from_cart_url() { if (isset($_GET['add-to-cart']) && strpos($_GET['add-to-cart'], 'gla_') === 0) { // Remove the 'gla_' prefix $product_id = str_replace('gla_', '', $_GET['add-to-cart']); // Redirect to the new URL without the 'gla_' prefix $redirect_url = add_query_arg('add-to-cart', $product_id, remove_query_arg('add-to-cart')); wp_redirect($redirect_url); exit; } }This code works as follows:
- Uses the
template_redirecthook to execute the function before the template is rendered. - Checks if the
add-to-cartparameter is present in the query and starts withgla_. - If the prefix is found, it removes the
gla_prefix from the product ID. - Creates a new URL without the prefix and redirects to it.
Thus, when a request is made with the
gla_prefix, it automatically redirects to the URL without this prefix.Hello. Thanks i update plugin to latest version and issues is resolved now)
Forum: Plugins
In reply to: [Redis Object Cache] Hi! Have error The ‘gutenkit-template-libraryWordPress 6.5 all is ok but in 6.6 and 6.6.1 this bug
Forum: Plugins
In reply to: [Plus WebP or AVIF] Bad Support the WoocommerceThere are also many other errors and memory leaks. The main problem is that when cleaning thumbnails, it does not clean everything and many original (sizes) thumbnails remain in the library.
SOLUTION:
Add to generate_webp in after
foreach ( (array) $metadata['sizes'] as $key => $value ) {code}$this->delete_old_thumbnails( $path, $metadata['file'], $metadata['sizes'], $pluswebp_settings['types'] );private function delete_old_thumbnails( $path, $original_file, $sizes, $types ) {
$base_name = pathinfo( $original_file, PATHINFO_FILENAME );
$dir = opendir( $path );
if ( $dir ) {
while ( ( $file = readdir( $dir ) ) !== false ) {
$file_info = pathinfo( $file );
if ( $file_info['basename'] !== $original_file &&
in_array( $file_info['extension'], $types ) &&
strpos( $file_info['filename'], $base_name ) !== false ) {
wp_delete_file( $path . $file_info['basename'] );
}
}
closedir( $dir );
}
}Maybe u help that in next update )
Forum: Plugins
In reply to: [Plus WebP or AVIF] Palette Image Not Supported and PHP Fatal ErrorOkay) I make own version plugin Macrus WebP and AVIF with all function) two day is ready and i will publish him Woocommerce Store)
“Maybe you can try replacing the images that generate the error manually and see if the plugin starts working correctly again.” – you must make “if” for solution skip TrueColors file:
My solution in another plugin i used:
private function create_webp(string $filename, string $mime_type, string $filename_webp): bool { if (!file_exists($filename) || file_exists($filename_webp)) { return false; } $pluswebp_settings = get_option('pluswebp'); @set_time_limit(60); wp_raise_memory_limit('pluswebp'); $src = null; $img = null; $ret = false; try { switch ($mime_type) { case 'image/jpeg': $src = imagecreatefromjpeg($filename); break; case 'image/png': $src = imagecreatefrompng($filename); break; case 'image/bmp': if (function_exists('imagecreatefrombmp')) { $src = imagecreatefrombmp($filename); } break; case 'image/gif': $src = imagecreatefromgif($filename); break; default: return false; // Unsupported MIME type } if (!$src) { return false; // Failed to create source image } $img = imagecreatetruecolor(imagesx($src), imagesy($src)); if (!$img) { imagedestroy($src); return false; // Failed to create destination image } switch ($mime_type) { case 'image/jpeg': $bgcolor = imagecolorallocate($img, 255, 255, 255); imagefill($img, 0, 0, $bgcolor); imagealphablending($img, true); break; case 'image/png': imagealphablending($img, false); imagesavealpha($img, true); break; case 'image/gif': $bgcolor = imagecolorallocatealpha($img, 0, 0, 0, 127); imagefill($img, 0, 0, $bgcolor); imagecolortransparent($img, $bgcolor); break; } imagecopy($img, $src, 0, 0, 0, 0, imagesx($src), imagesy($src)); $ret = imagewebp($img, $filename_webp, $pluswebp_settings['quality']); } catch (Exception $e) { // Handle exception if needed } finally { if ($src) { imagedestroy($src); } if ($img) { imagedestroy($img); } } return $ret; }And maybe you help that
Forum: Plugins
In reply to: [Plus WebP or AVIF] Palette Image Not Supported and PHP Fatal ErrorI did not understand the answer. But for me personally, I converted all the files, everything is stable and the main thing for me is that the analytics work.
Forum: Plugins
In reply to: [Plus WebP or AVIF] Palette Image Not Supported and PHP Fatal ErrorColleague, in my opinion, I believe that for such operations, everything needs to be at hand, and making this plugin all in one click would be great. Additionally, simply adding these options from your other plugin as a paid option would be perfect. That would be awesome. You could also add support for AVIF and name it “Plus WebP and AVIF.”
Hard work for class-pluswebp.php
- Enhanced Stability and Code Structure:
Started improvements in the main plugin file and CLI classes to enhance stability. Worked on organizing the code for better readability and modularity.
Main Plugin File:
The provided code ensures correct dependency loading. The approach using a function to check and include classes optimally manages dependencies. Next CLI Name: Plus WebP CLI Improvements:
- Readability and Modularity:
Extracted file missing messages intogenerate_missing_file_messagefunction for better readability inpluswebp_cli_command. - Optimized Message Handling:
Updated messages once after the main loop to minimize database calls. - Documentation and Comments:
Added comments for improved code understanding and documentation for new functions.
Further Improvements for
class PlusWebp:- function generate_webp:
- Modern array syntax used for clarity and optimized image handling to avoid potential memory leaks with large files.
- Helper Functions: Extracted reusable logic into separate helper functions.
- Readability: Improved readability by breaking down long functions into smaller, focused functions.
- Maintainability: Easier to maintain and update specific parts of the code without affecting others.
- Error Handling: More structured approach allows easier integration of error handling.
- function thumbnail_urls:
- Optimized checks to prevent memory leaks and considered scenarios where image attribute values are in
$image_attr_thumbnail.
- function output_datas:
- Updated to PHP 8 syntax, replacing
array()with[], optimized checks, and memory leak prevention for modern project compatibility. - Helper Functions: Extracted logic into separate helper functions get_original_image_info and get_file_size.
- Readability: Improved readability by breaking down the function into smaller, focused parts.
- Error Handling: More structured error handling for file size retrieval.
- Descriptive Variable Names: Used more descriptive variable names for clarity.
- function mail_messages:
- Enhanced stability and modern PHP practices. Utilizes
$messagevariable for message storage and returns an array with the latest message and an array of all messages for further processing. - Initialization of Variables: Initialized $messages to an empty array to ensure it’s always available.
- Improved Readability: Used sprintf to construct the message in a more readable and maintainable way.
- Consistent Message Formatting: Ensured consistent formatting by using sprintf for all parts of the message.
- Edge Case Handling: Added checks to handle potential empty values, ensuring the function behaves correctly even if some metadata is missing.
- function create_webp:
- Changes:
- Parameter and return types updated to
stringfor$filename,$mime_type,$filename_webp, andboolfor return value. - Memory leak prevention with
imagedestroy()after GD image processing. - Memory management using
wp_raise_memory_limit()for increased memory limit if needed. - Replaced
array()with[]for improved readability and PHP 8 compatibility. - Returns
falsefor unsupported MIME types or unsuccessful image creation attempts. - Error Handling: Using try-catch-finally ensures that resources are properly managed and potential errors are caught.
- Resource Management: Added checks and ensured that both $src and $img are always destroyed properly to prevent memory leaks.
- Simplified Control Flow: Reduced duplication by moving common operations outside of the switch statement.
- PHP 8.3 Compatibility: Ensured compatibility with PHP 8.3 by handling exceptions and potential errors more robustly.
- Parameter and return types updated to
- function change_ext:
- Changes:
- Parameter types updated to strict PHP types (
stringfor$before_file_name,$ext,boolfor$addext) for clarity and type safety. - Utilizes
pathinfo()for retrieving file extensions instead ofexplode()andend(), ensuring reliable extension retrieval. - Error Handling: The method now uses a try-catch block to handle potential exceptions that might arise, particularly when retrieving the file extension.
- Logging: The method logs both successful extension changes and errors. This is useful for debugging and monitoring the application.
- Return Original Filename on Error: If an error occurs, the method returns the original filename instead of potentially corrupting the filename.
- Usage of error_log: error_log is a simple and effective way to log messages to the server’s error log. It helps in tracking what went wrong if something doesn’t work as expected.
- Parameter types updated to strict PHP types (
- function change_db:
- Updates:
- Parameter types:
$before_urland$after_urldeclared asstringfor PHP 8 standards, enhancing type safety and clarity. - Uses
$wpdb->update()for safe database updates instead of direct SQL queries via$wpdb->query(). Includes data sanitization viaprepare()for secure WordPress table operations. - Added WHERE clause to restrict updates to posts containing
$before_url, improving query efficiency. - Key Improvements:
- Error Handling: The method now uses a try-catch block to handle potential exceptions that might arise during the database query.
- Validation: Checks to ensure that the URLs are not empty before proceeding with the query.
- Logging: Logs both successful operations and errors, providing more insights into the function’s execution.
- Descriptive Exception Messages: Provides detailed error messages to help diagnose the specific issue.
- Usage of error_log: error_log is used to log messages to the server’s error log, which helps track and diagnose issues.
- Example Log Messages:
- Success: “Successfully replaced URLs in the database: {before_url} to {after_url}”
- Error: “Error changing database content: {error message}”
- Parameter types:
- function upload_dir_url_path:
- Changes:
- Uses
[]instead ofarray()for returning arrays, adhering to modern PHP syntax. - Utilizes
wp_normalize_path()for path normalization. - Memory leak prevention with
realpath()for obtaining the real path. - Checks HTTPS connection with
is_ssl()for protocol correctness. - Conditional upload_path determination based on relative path availability.
- Uses
- function realurl:
- Enhancements:
- Replaces
array()with[]for declaring arrays. - Uses
stringtype hinting for function parameters for improved clarity. - Utilizes
wp_parse_urlfor parsing base URLs. - Uses double quotes for better readability when concatenating strings with variables.
- Simplified Logic: The function logic is simplified to handle base URLs with relative paths more effectively, using realpath() and wp_normalize_path() to ensure paths are correctly resolved.
- SSL Handling: set_url_scheme() is used to ensure URLs are HTTPS if the site is accessed over SSL, replacing manual string manipulation.
- Path Calculation: upload_path is calculated relative to site_url() for consistency and proper URL handling in WordPress.
- Usage of wp_parse_url and set_url_scheme:
- wp_parse_url: Used to parse and manipulate URLs in a WordPress-safe manner.
- set_url_scheme: Ensures URLs are properly prefixed with https:// if the site is accessed over SSL, handling security considerations automatically.
- Overall:
- This version of upload_dir_url_path ensures better compatibility with PHP 8.3, improves clarity and efficiency in handling paths and URLs, and adheres to best practices in WordPress development.
- Replaces
- function raise_memory_limit:
- Improvements:
- Added type hinting for parameter
$filtered_limitto ensure it’s a string. - Directly returns
'256M'for clarity and consistency.
- function control_mime_type:
- Improvements:
- Added type hinting for parameters
$image_mime_transforms(array) and$attachment_id(int) for PHP 8 compatibility. - Returns an empty array
[], ensuring clear function purpose and return type.
These enhancements aim to make the code more structured, maintainable, and compatible with modern PHP versions, particularly PHP 8.
This comprehensive report outlines the detailed improvements made across various functions and classes in your plugin, focusing on enhancing stability, readability, and compatibility with modern PHP standards.
I want to inform you that in this version, the correct logging approach has been implemented. Now, the logs will show the process of what it converts and what actions it performs.
New version: for test.. 4.09 https://www.sendspace.com/file/oxa040
Forum: Plugins
In reply to: [Plus WebP or AVIF] Palette Image Not Supported and PHP Fatal ErrorThank you for the mutual feedback. I would be very happy to help improve your plugin and make it more stable and faster overall. I also have recommendations to make it more resilient in terms of memory usage because it indeed has a large amount of memory leaks during operation. Specifically, I think it would be great to develop micro-control over the execution of BULK tasks. Instead of executing tasks en masse (i.e., converting and replacing all files at once), it should perform them step-by-step. For instance, it should find an image, check its dependency (whether it is properly linked), and if it is missing from the WordPress Media Library but physically present as a link (which can happen when people manually add files to the /uploads/year/date/ directory), our task would be to identify its place in the post (blog). If the file is identified there, we would automatically add it to the WordPress Media Library as it should be, but already as a generated WEBP file with the correct MIME type.
Sometimes people add images incorrectly, bypassing the typical upload through Media, so these images lack MIME types, meta information, etc. During such tests, I confirmed that these images are not converted and simply exist in certain places. To convert them, we need pre-functions that will additionally scan, find these files, and correctly place them in the WordPress Media Library. After that, the new link and ID would be inserted correctly in the post where the original file was identified, which was added manually through FTP, for example, to wp-content/2024/05/.
We can then convert the file or first add it correctly to the media and then convert it, depending on what is more precise and faster. Overall, I think for such operations, a pre-scan button is essential to clear all thumbnails before processing. Then, we scan only the original files. After scanning, we proceed with conversion, make the necessary changes in the database, and add the files correctly. Finally, after completing the task, we generate all thumbnails from the WEBP files.
Steps for Improving the Plugin:
- Micro-Control of BULK Tasks:
- Implement step-by-step execution instead of processing all files at once.
- Example: Find an image, check its dependency, and handle it individually.
- Handling Images Added Manually:
- Identify images manually added to the
/uploads/year/date/directory. - Ensure these images are properly linked and added to the WordPress Media Library with correct MIME types.
- Pre-Functions for Scanning and Adding Images:
- Develop pre-functions to scan for manually added images.
- Add these images to the WordPress Media Library before conversion.
- Automatic Conversion and Correct Placement:
- Convert identified images to WEBP format with correct MIME types.
- Ensure the new link and ID are correctly inserted in the post where the original file was found.
- Pre-Scan Button:
- Add a pre-scan button to clear all thumbnails before processing.
- Scan only the original files for further operations.
- Processing and Database Updates:
- After scanning, proceed with conversion and make necessary changes in the database.
- Add files correctly and generate thumbnails from the WEBP files after completing the task.
- Optimize for Memory Usage:
- Address memory leaks during plugin operation.
- Make the plugin more resilient in terms of memory usage.
These steps should help in enhancing the plugin’s stability, speed, and overall performance.
Forum: Plugins
In reply to: [Plus WebP or AVIF] Palette Image Not Supported and PHP Fatal ErrorPS. Maybe you have a Hook for delete all original files + thumbnails from uploads ?? I see more thumbnails files what not deleted after convertion.. How can i remove that from you plugin?
Forum: Plugins
In reply to: [Plus WebP or AVIF] Palette Image Not Supported and PHP Fatal ErrorThe issue arises when a file exists in the WordPress database but is physically absent on the server in the
uploads/directory. In such cases,filesize()cannot access the file because it doesn’t exist physically. Additionally, if the MIME type exists but the file doesn’t, you haven’t handled this scenario. Investigation of the error reveals that when the file is not found or there’s no access to it, PHP throws a warning:filesize(): stat failed for, which halts further execution. Essentially, the process stops at this error and doesn’t proceed.To address this, I installed your latest plugin version and made specific changes to the
public function generate_webp( $metadata, $attachment_id ) {function. I added logging to ensure the code works under all conditions, even when the file is physically absent or inaccessible. The code logs when the file is not found or inaccessible and continues its operation. However, I cannot guarantee this is the correct approach without knowing all nuances of your code and how your plugin handles scenarios where a file exists in WordPress Media as META but is physically missing.I recommend investigating this behavior during file conversions. Simply delete the file from
wp-content/uploads/without removing it via WordPress Media, then conduct the conversion to track this error.Additionally, here is the revised function with your provided code:
/** * Webp generate * * @param array $metadata metadata. * @param int $attachment_id ID. * @return array $metadata metadata. * @since 1.00 */ public function generate_webp( $metadata, $attachment_id ) { $pluswebp_settings = get_option( 'pluswebp' ); $replace = $pluswebp_settings['replace']; $mime_type = get_post_mime_type( $attachment_id ); if ( in_array( $mime_type, $pluswebp_settings['types'] ) ) { $metadata_webp = $metadata; $file_webp = $this->change_ext( $metadata['file'], 'webp', $pluswebp_settings['addext'] ); $metadata_webp['file'] = $file_webp; if ( '.' === dirname( $file_webp ) ) { $dir_name_url = '/'; $dir_name_path = wp_normalize_path( '/' ); } else { $dir_name_url = '/' . dirname( $file_webp ) . '/'; $dir_name_path = wp_normalize_path( $dir_name_url ); } $url = $this->upload_url . $dir_name_url; $path = $this->upload_dir . $dir_name_path; foreach ( (array) $metadata['sizes'] as $key => $value ) { $file_thumb = $value['file']; $file_thumb_webp = $this->change_ext( $file_thumb, 'webp', $pluswebp_settings['addext'] ); $ret = $this->create_webp( $path . $file_thumb, $mime_type, $path . $file_thumb_webp ); if ( $ret ) { $metadata_webp['sizes'][ $key ]['file'] = $file_thumb_webp; $metadata_webp['sizes'][ $key ]['mime-type'] = 'image/webp'; // Check if file exists before getting its size $webp_file_path = $path . wp_basename( $file_thumb_webp ); if ( file_exists( $webp_file_path ) ) { $webp_size = filesize( $webp_file_path ); $metadata_webp['sizes'][ $key ]['filesize'] = $webp_size; } else { // Log that the file was not found error_log( "File not found on server: $webp_file_path" ); $metadata_webp['sizes'][ $key ]['filesize'] = 'File not found'; } if ( $replace ) { wp_delete_file( $path . $file_thumb ); $this->change_db( $url . $file_thumb, $url . $file_thumb_webp ); } } } $org_img_file = null; if ( array_key_exists( 'original_image', $metadata ) && ! empty( $metadata['original_image'] ) ) { $org_img_file = wp_normalize_path( wp_get_original_image_path( $attachment_id, false ) ); $org_webp_file = $this->change_ext( $org_img_file, 'webp', $pluswebp_settings['addext'] ); $ret = $this->create_webp( $org_img_file, $mime_type, $org_webp_file ); if ( $ret ) { $metadata_webp['original_image'] = wp_basename( $org_webp_file ); } } $ret = $this->create_webp( $this->upload_dir . '/' . $metadata['file'], $mime_type, $path . wp_basename( $file_webp ) ); $webp_file_path = $path . wp_basename( $file_webp ); // Check if file exists before getting its size if ( file_exists( $webp_file_path ) ) { $webp_size = filesize( $webp_file_path ); $metadata_webp['filesize'] = $webp_size; } else { // Log that the file was not found error_log( "File not found on server: $webp_file_path" ); $metadata_webp['filesize'] = 'File not found'; } if ( $ret ) { if ( $replace ) { $up_post = array( 'ID' => $attachment_id, 'guid' => $this->upload_url . '/' . $file_webp, 'post_mime_type' => 'image/webp', ); wp_update_post( $up_post ); update_post_meta( $attachment_id, '_wp_attached_file', $file_webp ); /* for bulk generate */ update_post_meta( $attachment_id, '_wp_attachment_metadata', $metadata_webp ); /* delete org file */ wp_delete_file( $this->upload_dir . '/' . $metadata['file'] ); if ( $org_img_file ) { wp_delete_file( $org_img_file ); } /* Replace */ $this->change_db( $this->upload_url . '/' . $metadata['file'], $this->upload_url . '/' . $file_webp ); /* for hook */ $metadata = $metadata_webp; /* for mail */ $attach_id = $attachment_id; } else { $post = get_post( $attachment_id ); $title = $post->post_title; $attachment = array( 'guid' => $this->upload_url . '/' . $file_webp, 'post_mime_type' => 'image/webp', 'post_title' => $title, 'post_content' => '', 'post_status' => 'inherit', ); $file = $this->upload_dir . '/' . $file_webp; $attach_id = wp_insert_attachment( $attachment, $file ); /* for XAMPP [ get_attached_file( $attach_id ): Unable to get correct value ] */ $metapath_name = str_replace( $this->upload_dir . '/', '', $file ); update_post_meta( $attach_id, '_wp_attached_file', $metapath_name ); wp_update_attachment_metadata( $attach_id, $metadata_webp ); $author = get_userdata( $post->post_author ); $userid = $author->ID; $postdate = get_the_date( 'Y-m-d H:i:s', $attachment_id ); $postdategmt = get_gmt_from_date( $postdate ); $up_post = array( 'ID' => $attach_id, 'post_author' => $userid, 'post_date' => $postdate, 'post_date_gmt' => $postdategmt, 'post_modified' => $postdate, 'post_modified_gmt' => $postdategmt, ); wp_update_post( $up_post ); } update_option( 'pluswebp_generate', $attach_id ); /* for Media Library folders term by Organize Media Folder */ do_action( 'omf_folders_term_update', $metadata_webp, $attach_id ); /* for Term filter update by Organize Media Folder */ do_action( 'omf_term_filter_update' ); } } return $metadata; }This function includes logging and handling for scenarios where files are not found or inaccessible, aiming to continue processing despite these errors.