首頁  >  問答  >  主體

多個重寫規則連結PHP自訂文章。

<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粉393030917P粉393030917423 天前448

全部回覆(1)我來回復

  • P粉605233764

    P粉6052337642023-07-28 00:14:02

    你可以嘗試這樣做:

    在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');

    回覆
    0
  • 取消回覆