多个重写规则链接PHP自定义文章。
P粉393030917
P粉393030917 2023-07-27 12:19:25
0
1
373
<p>我是PHP的新手,我尝试做一些重写规则来改变一些链接的结构。我尝试了一些找到的代码,这段代码只适用于我在for循环中指定的第一个自定义文章类型。我想要做一个for循环,来改变我指定的所有自定义文章类型的链接(这些文章类型的名称在一个数组中),这是我的重写规则代码:</p> <pre class="brush:php;toolbar:false;">function mycustomname_link($post_link, $post = 0) { if($post->post_name === $name_of_my_post) { return home_url('new' .'/'. 'posts'.'/'. $post->post_name .'/'. $post->ID . '/'); } else{ return $post_link; } } add_filter('post_type_link', 'mycustomname_link', 1,3); function mycustomname_rewrites_init(){ add_rewrite_rule('new/posts/([^/]+)/([0-9]+)?$', 'index.php?post_type=nature_posts&p=$matches[1]&p=$matches[2]', 'top'); flush_rewrite_rules(); } add_action('init', 'mycustomname_rewrites_init'); </pre> <p>我看到函数中有一个返回语句,所以它只会在第一次迭代和第一个自定义文章名称上应用重写规则,我该如何做一个for循环,使其适用于我指定的所有post_names,并且不会在第一次迭代时停止?</p>
P粉393030917
P粉393030917

全部回复(1)
P粉605233764

你可以尝试这样做:

在mycustomname_link函数中,我们添加了一个循环,遍历$custom_post_types数组。对于每个自定义文章类型,它会检查当前的文章类型是否与数组中的任何名称匹配。如果有匹配,将应用重写规则。
同样,在mycustomname_rewrites_init函数中,我们添加了一个循环来注册所有自定义文章类型的重写规则。每个自定义文章类型都将有自己的重写规则。

通过这种修改,重写规则将应用于$custom_post_types数组中指定的所有自定义文章类型,而不会在第一次迭代时停止。确保更新$custom_post_types数组,其中包含你想在重写规则中包含的所有自定义文章类型的名称。


function mycustomname_link($post_link, $post = 0) {
    $custom_post_types = array('name_of_my_post', 'another_post_type', 'yet_another_post_type'); // Add all your custom post type names here

    foreach ($custom_post_types as $post_type) {
        if ($post->post_type === $post_type) {
            return home_url('new' .'/'. 'posts'.'/'. $post->post_name .'/'. $post->ID . '/');
        }
    }

    return $post_link;
}
add_filter('post_type_link', 'mycustomname_link', 10, 2);

function mycustomname_rewrites_init(){
    $custom_post_types = array('name_of_my_post', 'another_post_type', 'yet_another_post_type'); // Add all your custom post type names here

    foreach ($custom_post_types as $post_type) {
        add_rewrite_rule('new/posts/([^/]+)/([0-9]+)?$', 'index.php?post_type=' . $post_type . '&p=$matches[1]&p=$matches[2]', 'top');
    }

    flush_rewrite_rules();
}
add_action('init', 'mycustomname_rewrites_init');
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!