😍How to Customize the URL of Attachments in WordPress (ok)

https://www.rafaelcardero.com/media/wordpress-customize-attachment-url-src-dl/

Study

C:\xampp82\htdocs\wp2\wp-content\themes\twentyseventeen\functions.php

function ns_add_rewrite_rules($rules){
	$dirname = 'media';
	$custom_rules = array("{$dirname}/(.?.+?)/?$" => 'index.php?attachment=$matches[1]');
	return array_merge($custom_rules, $rules);
}
add_filter('rewrite_rules_array', 'ns_add_rewrite_rules', 10, 1);
/*
* Adds the 'media' directory to the URL of an attachment.
*/
function ns_normalize_attachment_url($url, $post_ID){
	$dirname = 'media';
	$post = get_post($post_ID);
	return $post ? sprintf('%s/%s/%s/', home_url(), $dirname, $post->post_name) : $url;
}
add_filter('attachment_link', 'ns_normalize_attachment_url', 10, 2);
/*
* Adds the '-dl' suffix to the name of an attachment.
*/
function ns_normalize_attachment_name($data, $postarr){
	$suffix = "-" . get_the_ID();
	$has_suffix = substr($data['post_name'], -strlen($suffix)) === $suffix;
	$add_suffix = isset($postarr['ID']) && !$has_suffix;
	if($add_suffix){
			$desired_name = $data['post_name'] . $suffix;
			$data['post_name'] = wp_unique_post_slug($desired_name, $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent']);
	}
	return $data; 
}
add_filter('wp_insert_attachment_data', 'ns_normalize_attachment_name', 10, 2);

Trước

Sau

Example

C:\xampp82\htdocs\wp3\wp-content\themes\gutener-child\attachment.php

C:\xampp82\htdocs\wp3\wp-content\themes\gutener-child\template-parts\content-attachment.php

Last updated

Was this helpful?