Wordpress自定义帖子类型根据自定义字段重写永久链接

时间:2018-06-30 22:02:25

标签: wordpress url-rewriting custom-post-type permalinks

我需要能够将自定义帖子类型帖子的永久链接重写为:

  

{post-id} .domain.com

并且如果该帖子的{custom-field-1}具有值,请执行以下操作:

  

{custom-field-1} .domain.com

是否可以使用wp_rewrite api做到这一点,或者在后期注册代码中提供一些方法?

顺便说一句-我现在的(糟糕)方法是:

  1. 将通配符添加到我的域(* .domain.com)。

  2. 在我的索引文件中,我使用php检查url是什么以及是否是ubdomain。

  3. 如果这是我得到的子域部分(“ that-part” .domain.com),并检查我的帖子中特定自定义字段中是否存在带有此值的帖子,或者是否有此ID的帖子,然后将$ post数据设置为该帖子,并为该帖子类型添加正确的模板文件。

我知道这是一个不好的方法。但这是我目前唯一知道的方法,希望您能帮助您找到更好的解决方案。

1 个答案:

答案 0 :(得分:0)

您已经尝试了什么?到目前为止,wp_rewrite似乎是最简单的解决方案。

不确定在不使用任何.htaccess修改的情况下如何对子域执行此操作。但是,如果基于根域;以下[unested]解决方案可能会起作用:

function custom_rewrite() {
  if ( ! get_post_meta( 'your_key', get_the_ID() ) ) {
    add_rewrite_rule( '^' . get_the_ID(), 'index.php?post_id=' . get_the_ID() . ', 'top' );
  } else {
    add_rewrite_rule( '^' . get_post_meta( 'your_key', get_the_ID() ), 'index.php?post_id=' . get_the_ID() . ', 'top' );
  }
}
add_action( 'init', 'custom_rewrite' );