Last active
November 10, 2020 13:47
-
-
Save kussberg/87ded391fee89ca4dc0b4982787b2469 to your computer and use it in GitHub Desktop.
Wordpress: Enable SVG in Media; Fix slug conflict of attachments and posts; Redirect media to files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Allow SVG in Media | |
function cc_mime_types($mimes) { | |
$mimes['svg'] = 'image/svg+xml'; | |
return $mimes; | |
} | |
add_filter('upload_mimes', 'cc_mime_types'); | |
// Redirect media pages to source files | |
add_action( 'template_redirect', 'test_attachment_redirect', 10 ); | |
function test_attachment_redirect() { | |
if( is_attachment() ) { | |
$url = wp_get_attachment_url( get_queried_object_id() ); | |
wp_redirect( $url, 301 ); | |
} | |
return; | |
} | |
// Change the slug of attachments to resolve conflict with pages or posts | |
add_filter( 'wp_unique_post_slug', 'wpse17916_unique_post_slug', 10, 6 ); | |
function wpse17916_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) { | |
if ( 'attachment' == $post_type ) | |
$slug = $original_slug . uniqid( '-' ); | |
return $slug; | |
} | |
// Fix existing conflicts of slugs with attachments | |
function wp21418_append_to_post_name() { | |
// Checks to see if the option images_updated has been set or has a value of true. | |
if ( get_option( 'images_updated' ) === 'true' ) : | |
return; | |
endif; | |
// get all attachment posts. | |
$attachments = get_posts([ | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'name' => $p->slug, | |
'posts_per_page' => -1, | |
]); | |
// For each attachment, loop and update the post_name | |
foreach($attachments as $p){ | |
$attachment = array( | |
'ID' => $p->ID, | |
'post_name' => $p->post_name.'-image' | |
); | |
// Update the post into the database | |
wp_update_post( $attachment ); | |
} | |
// Once everything is looped, add the option to the database. | |
add_option( 'images_updated', 'true' ); | |
} | |
add_action( 'after_setup_theme', 'wp21418_append_to_post_name' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment