I am trying to add a suffix having certain values (such as min123) to all image URLs on my WordPress website getallnumber.com. The images are located in "/wp-content/uploads/year/month/". After adding the value the URL should be /wp-content/uploads/year/month/image.min123.png. I tried some pieces of codes including the sanitize code but there is no lock. Please help me out!
function sa_sanitize_special_chars ($filename) {
$f=remove_accents( $filename );
return 'min123-'.$f;
}
Add below code snippet in your active theme's functions.php file -
// wp media name suffix on upload
function modify_wp_handle_upload_prefilter( $file ) {
if( isset( $file['name'] ) ) {
$fileinfo = pathinfo( $file['name'] );
if( $fileinfo && isset( $fileinfo['filename'] ) && isset( $fileinfo['extension'] ) ) {
$suffix = 'min123'; // your suffix goes here
$name = $fileinfo['filename'] . '.' . $suffix . '.' . $fileinfo['extension'];
$file['name'] = $name;
}
}
return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'modify_wp_handle_upload_prefilter', 99 );
Related
i want to edit theme from theme editor page in wordpress
i taked error :
Fatal error: Maximum execution time of 300 seconds exceeded in gillion\wp-includes\class-wp-theme.php on line 1401
however when i changed theme This problem is solved
code line 1401 class-wp-theme.php
$exclusions = (array) apply_filters( 'theme_scandir_exclusions', array( 'CVS', 'node_modules', 'vendor', 'bower_components' ) );
foreach ( $results as $result ) {
if ( '.' === $result[0] || in_array( $result, $exclusions, true ) ) {
continue;
}
if ( is_dir( $path . '/' . $result ) ) {
if ( ! $depth ) {
continue;
}
$found = self::scandir( $path . '/' . $result, $extensions, $depth - 1, $relative_path . $result );
$files = array_merge_recursive( $files, $found );
} elseif ( ! $extensions || preg_match( '~\.(' . $_extensions . ')$~', $result ) ) {
$files[ $relative_path . $result ] = $path . '/' . $result;
}
}
return $files;
}
i don't see any error syntax
The things I did:
check file .htaccess
increase memory php
disable plugin
change theme that problem was solved
when i use the code:
add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');
function my_nofollow($content) {
return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}
function my_nofollow_callback($matches) {
$link = $matches[0];
$site_link = get_bloginfo('url');
if (strpos($link, 'rel') === false) {
$link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
} elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
$link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
}
return $link;
}
only in the_content and the_excerpt the links get a nofollow attribute. How i can edit the code, that the whole wordpress site use this functions (footer, sidebar...)
Thank you
a good script which allows to add nofollow automatically and to keep the other attributes
function nofollow(string $html, string $baseUrl = null) {
return preg_replace_callback(
'#<a([^>]*)>(.+)</a>#isU', function ($mach) use ($baseUrl) {
list ($a, $attr, $text) = $mach;
if (preg_match('#href=["\']([^"\']*)["\']#', $attr, $url)) {
$url = $url[1];
if (is_null($baseUrl) || !str_starts_with($url, $baseUrl)) {
if (preg_match('#rel=["\']([^"\']*)["\']#', $attr, $rel)) {
$relAttr = $rel[0];
$rel = $rel[1];
}
$rel = 'rel="' . ($rel ? (strpos($rel, 'nofollow') ? $rel : $rel . ' nofollow') : 'nofollow') . '"';
$attr = isset($relAttr) ? str_replace($relAttr, $rel, $attr) : $attr . ' ' . $rel;
$a = '<a ' . $attr . '>' . $text . '</a>';
}
}
return $a;
},
$html
);
}
The idea is to add your action in the full html buffer, once everything is loaded and filtered, not only in the 'content' area.
BE VERRY CAREFULL WITH THIS !!!! This action is verry RAW and low-level... You can really mess up everything with theses buffer actions. But it's also very nice to know ;-)
It works like this :
add_action( 'wp_loaded', 'buffer_start' ); function buffer_start() { ob_start( "textdomain_nofollow" ); }
add_action( 'shutdown', 'buffer_end' ); function buffer_end() { ob_end_flush(); }
Then do the replace action and setup the callback :
Juste imagine the $buffer variable as your full site in HTML, as it will load.
function textdomain_nofollow( $buffer ) {
return preg_replace_callback( '/<a[^>]+/', 'textdomain_nofollow_callback', $buffer );
}
Here is how I do the href checking (read my comments) :
function textdomain_nofollow_callback( $matches ) {
$link = $matches[0];
// if you need some specific external domains to exclude, just use :
//$exclude = '('. home_url() .'|(http|https)://([^.]+\.)?(domain-to-exclude.org|other-domain-to-exclude.com)|/)';
// By default, just exclude your own domain, and your relative urls that starts by a '/' (if you use relatives urls)
$exclude = '('. home_url() .'|/)';
if ( preg_match( '#href=\S('. $exclude .')#i', $link ) )
return $link;
if ( strpos( $link, 'rel=' ) === false ) {
$link = preg_replace( '/(?<=<a\s)/', 'rel="nofollow" ', $link );
} elseif ( preg_match( '#rel=\S(?!nofollow)#i', $link ) ) {
$link = preg_replace( '#(?<=rel=.)#', 'nofollow ', $link );
}
return $link;
}
It works well in my experience...
Q
I'm attempting to add a feature to a plugin that extends media management. This feature would allow you to rename an attachment file. I've been able to complete this with the following code.
public function update_attachment_filename( $post_ID ) {
// Get path to existing file
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Generate new file name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the name and reference to file
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
}
While the original file gets renamed using the above method, all additional image sizes defined in the plugins/theme are not updated. I'm struggling to figure out the best way to accomplish this task.
I've looked into wp_update_attachment_metadata() and wp_generate_attachment_metadata() but am unsure whether they will give me the desired functionality.
Additionally I've looked into something such as:
$file_meta = wp_get_attachment_metadata( $post_ID );
foreach( $file_meta['sizes'] as $image ) {
// Do something
}
Any nudge in the right direction would be greatly appreciated.
Thanks!
I was able to utilize both the wp_generate_attachment_metadata() and the wp_update_attachment_metadata() function to achieve the desired end result.
public function update_attachment_filename( $post_ID ) {
if( isset( $_POST['update_filename'] ) && ! empty( $_POST['update_filename'] ) ) {
// Get path to existing attachment
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Create new attachment name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the attachment name
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
// Update attachment meta data
$file_updated_meta = wp_generate_attachment_metadata( $post_ID, $file_updated );
wp_update_attachment_metadata( $post_ID, $file_updated_meta );
}
}
I am working on a wordpress theme. It is almost complete. When i check it in theme-check plugin it give the warning
WARNING: file_get_contents was found in the file sources.php File operations
should use the WP_Filesystem methods instead of direct PHP filesystem calls.
Line 84: $fonts = file_get_contents(dirname(__FILE__) . '/gwf.json');
Then i change file_get_contents to WP_Filesystem but it not getting the value or not working.
Here is the code of line 84:
function vp_get_gwf_family()
{
$fonts = file_get_contents(dirname(__FILE__) . '/gwf.json');
$fonts = json_decode($fonts);
$fonts = array_keys(get_object_vars($fonts));
foreach ($fonts as $font)
{
$result[] = array('value' => $font, 'label' => $font);
}
return $result;
}
I was having problems with wp_filesystem due to security settings on the server and ended up changing:
global $wp_filesystem;
$file = $wp_filesystem->get_contents( get_template_directory() . '/assets/js/icomoon-selection.json' );
to:
ob_start();
include dirname(__FILE__) .'/../assets/js/icomoon-selection.json';
$file = ob_get_contents();
ob_end_clean();
Maybe it solves your warnings (the example use of wp filesystem or the workaround).
I was facing the same problem. I used these function to solve it.
public function icon_generator() {
$file = THEMEOO_THEME_DIR . 'inc/icon/fa-icons.json';
if ( is_readable( $file ) ) {
$icons = WP_Filesystem_Direct::get_contents( $file ); // phpcs:ignore WordPressVIPMinimum.Performance.FetchingRemoteData.FileGetContentsUnknown
if ( ! empty( $icons ) ) {
$icons = json_decode( $icons );
if ( isset( $icons->icons ) && ! empty( $icons->icons ) ) {
foreach ( $icons->icons as $icon ) {
echo '<span class="ti-' . esc_attr( $icon ) . '">';
}
}
}
}
die();
}
I think this will solve your problem. For better understanding you can follow this tutorial
If you can't get $wp_filesystem because you are not in the admin environment (e.g. if you are using REST API from wordpress, which is not an "admin" environment), then you can use php's native file_get_contents to replace $wp_filesystem->get_contents().
The param you need to pass into file_get_content() is the string that's after localhost:8080
e.g. for this local file:
http://localhost:8080/wp-content/uploads/2021/11/imagexyz.jpeg
You can acces it by:
$image_content = file_get_contents('wp-content/uploads/2021/11/imagexyz.jpeg');
I have the following code in my Wordpress. I need to add every uploaded image a counting number like, image_1, image_2, image_3 and so on..
The purpose of this is that every uploaded image attached to post, gets post ID name, and counting number in end to it.
It would be great if some one help me with this. Thanks!
<?php
add_filter('wp_handle_upload_prefilter', 'wpse_25894_handle_upload_prefilter');
add_filter('wp_handle_upload', 'wpse_25894_handle_upload');
function wpse_25894_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $file;
}
function wpse_25894_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $fileinfo;
}
function wpse_25894_custom_upload_dir($path)
{
/*
* Determines if uploading from inside a post/page/cpt - if not, default Upload folder is used
*/
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path; //error or uploading not from a post/page/cpt
/*
* Save uploads in ID based folders
*
*/
$customdir = '/' . $_REQUEST['post_id'];
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( 'image_make_intermediate_size', 'wpse_123240_rename_intermediates' );
function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Build our new image name
$postid = $_REQUEST['post_id'];
$random = rand(1,5);
$new_name = $dir . $postid . '_' . $random . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
?>
Now this code generates images named postid_randomnumber.jpg
I just need to add 20 images at maximum, so if I can have numbers from 1-20, that is also working fine with my purposes.
-- UPDATE --
I canged the last part of code to this, it is not maybe the cleanest solution, but it works:
function wpse_123240_rename_intermediates( $image )
{
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
//$count = get_option( 'wpa59168_counter', 1 );
// Build our new image name
$postid = $_REQUEST['post_id'];
$increment = 1;
$new_name = $dir . $postid . '_1' . $ext;
while(is_file($new_name)) {
$increment++;
$new_name = $dir . $postid . '_' . $increment . $ext;
}
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}