简体   繁体   English

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

[英]Wordpress Custom post type rewrite permalink based on custom field

I need to be able to rewrite the permalink of custom post type posts to: 我需要能够将自定义帖子类型帖子的永久链接重写为:

{post-id}.domain.com {post-id} .domain.com

and if {custom-field-1} of the post has a value, to: 并且如果该帖子的{custom-field-1}具有值,则执行以下操作:

{custom-field-1}.domain.com {custom-field-1} .domain.com

Is it possible to do it with the wp_rewrite api, or in the post registering code some how? 是否可以使用wp_rewrite api来做到这一点,或者在后期注册代码中如何做?

BTW - the (awful) way i do it now is by: 顺便说一句-我现在的(糟糕)方法是:

  1. Adding a wild card to my domain (*.domain.com). 将通配符添加到我的域(* .domain.com)。

  2. On my index file i check with php what is the url and if it is a ubdomain or not. 在我的索引文件中,我用php检查url是什么,以及它是否是ubdomain。

  3. if it is i get the subdomain part ("that-part".domain.com) and check if theres a post with this value in the specific custom field in my posts or is there a post with this id and if there is then is set the $post data to that post and include the right template file for that post type. 如果是的话,我得到了子域的一部分(“ that-part” .domain.com),并检查我的帖子中特定自定义字段中是否存在带有该值的帖子,或者是否存在具有此ID的帖子,是否存在将$ post数据设置为该帖子,并包括该帖子类型的正确模板文件。

I know it's a bad way to that. 我知道这是一个不好的方法。 but that's the only way i know how for now, hope you will help getting to a better solution. 但这是我目前所知道的唯一方法,希望您能帮助您找到更好的解决方案。

What have you already tried? 您已经尝试了什么? As wp_rewrite seems like the easiest solution so far. 到目前为止, wp_rewrite似乎是最简单的解决方案。

Not sure how you'd do this for a sub-domain without the use of any .htaccess amends. 不知道如何在不使用任何.htaccess修改的情况下对子域执行此操作。 However, if based on the root domain; 但是,如果基于根域; the below [untested] solution may work: 以下[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' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM