【问题标题】:Use Custom Post Type post ID in permalink rather than post title在永久链接中使用自定义帖子类型帖子 ID 而不是帖子标题
【发布时间】:2017-02-20 07:07:14
【问题描述】:

我有一个“员工”的自定义帖子类型。我正在尝试重写 slug 以使用帖子 ID 而不是默认帖子标题。在“重写”下的自定义帖子类型功能中是否有一种简单的方法可以做到这一点?

类似这样的:

   'rewrite' => [
        'with_front' => false,
        'slug' => 'employee/' . %post_id%,
    ]

【问题讨论】:

    标签: php wordpress url-rewriting custom-post-type slug


    【解决方案1】:

    在一个较旧的项目(未经测试)中,以下对我来说同样有效:

    'rewrite' => array(
        'with_front' => false,
        'slug' => 'news/events/%employee_id%'
    )
    
    
    add_filter('post_type_link', 'custom_employee_permalink', 1, 3);
    function custom_employee_permalink($post_link, $id = 0, $leavename) {
        if ( strpos('%employee_id%', $post_link) === 'FALSE' ) {
            return $post_link;
        }
        $post = &get_post($id);
        if ( is_wp_error($post) || $post->post_type != 'employee' ) {
            return $post_link;
        }
        return str_replace('%employee_id%', $post->ID, $post_link);
    }
    

    【讨论】:

      【解决方案2】:

      这是一种用自定义帖子类型永久链接结构中的帖子 ID 替换帖子标签的方法。

      改变

      somedomain.com/some-permalink/post_slug

      somedomain.com/some-permalink/123

      假设帖子类型已经存在

      'rewrite' => array('slug' => 'some-type')

      function _post_type_rewrite() {
      global $wp_rewrite;
      
      // Set the query arguments used by WordPress
      $queryarg = 'post_type=some-type&p=';
      
      // Concatenate %cpt_id% to $queryarg (eg.. &p=123)
      $wp_rewrite->add_rewrite_tag( '%cpt_id%', '([^/]+)', $queryarg );
      
      // Add the permalink structure
      $wp_rewrite->add_permastruct( 'some-type', '/some-type/%cpt_id%/', false );
      }
        add_action( 'init', '_post_type_rewrite' );
      
      /**
        * Replace permalink segment with post ID
        *
        */
      function _post_type_permalink( $post_link, $id = 0, $leavename ) {
      global $wp_rewrite;
      $post = get_post( $id );
      if ( is_wp_error( $post ) )
          return $post;
      
          // Get post permalink (should be something like /some-type/%cpt_id%/
          $newlink = $wp_rewrite->get_extra_permastruct( 'some-type' );
      
          // Replace %cpt_id% in permalink structure with actual post ID
          $newlink = str_replace( '%cpt_id%', $post->ID, $newlink );
          $newlink = home_url( user_trailingslashit( $newlink ) );
      return $newlink;
        }
       add_filter('post_type_link', '_post_type_permalink', 1, 3);
      

      来源:https://joebuckle.me/quickie/wordpress-replace-post-name-slug-post-id-custom-post-types/

      【讨论】:

        猜你喜欢
        • 2016-03-28
        • 2018-07-03
        • 2013-01-28
        • 2018-08-26
        • 2020-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多