admin管理员组文章数量:1327849
I found a very good code snippet to add a "base" into URL of blog posts: Custom permalink structure with a prefix just for posts
I tested it and it works great for post_type
: post
(to test it I created a "Must Use Plugin" in wp-content/mu-plugins/rewrite-me.php
with the PHP code).
I tried to modify it for Media by changing post
to attachment
but it doesn't work... Could you please tell me what's wrong with it?
Ideally I don't want to use a plugin for this. I would like all attachments (media) links to have a base in URLs. For example image my-cat.jpg
gets by default permalink/slug example/my-cat
but I would prefer if it can get example/someprefix/my-cat
. Could you please help me with that?
<?php
add_filter('pre_post_link', 'se332921_pre_post_link', 20, 3);
add_filter('post_rewrite_rules', 'se332921_post_rewrite_rules');
/**
* @param string $permalink The site's permalink structure.
* @param WP_Post $post The post in question.
* @param bool $leavename Whether to keep the post name.
*/
function se332921_pre_post_link($permalink, $post, $leavename)
{
if ( $post instanceof WP_Post && $post->post_type == 'attachment')
$permalink = '/attachment-prefix'.$permalink;
return $permalink;
}
/**
* @param array $post_rewrite The rewrite rules for posts.
*/
function se332921_post_rewrite_rules($post_rewrite)
{
if ( is_array($post_rewrite) )
{
$rw_prefix = [];
foreach( $post_rewrite as $k => $v) {
$rw_prefix[ 'attachment-prefix/'.$k] = $v;
}
//
// merge to keep original rules
$post_rewrite = array_merge($rw_prefix, $post_rewrite);
//
// or return only prefixed:
// $post_rewrite = $rw_prefix;
}
return $post_rewrite;
}
Thank you ;-).
Kind regards,
Ben
本文标签: Code snippet to add filter prepostlink to change Media URL (posttype attachment permalinkslug)
版权声明:本文标题:Code snippet to add filter pre_post_link to change Media URL (post_type attachment permalinkslug) 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742219080a2435108.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论