WordPress.org

Ready to get started?Download WordPress

Forums

post_type_link filter working but returns 404 (6 posts)

  1. Sebastien Couture
    Member
    Posted 3 years ago #

    I've got a custom post type for which I wanted to modify the URL to show the name of the product and the brand name, (a taxonomy).

    Here is my code

    <blockquote>
    
    add_filter('post_type_link', 'custom_post_link', 1, 3);
    
    function custom_post_link( $post_link, $id = 0 )
    {
    	$post = get_post($id);
    	if ( is_object($post) || $post->post_type == 'products' )
    	{
    		$terms = wp_get_object_terms($post->ID, 'brands');
    		if ($terms)
    		{
    			return $post_link . '-by-' . $terms[0]->slug . '.html';
    		}
    	}
    	else
    	{
    		return $post_link;
    	}
    }</blockquote>

    When I save my post, the permalink generates properly to
    /products/name-of-my-product-by-brand.html and the URLs are shown correctly when called with the_permalink(). Just one problem, calling the URL return a 404. Is there a custom rewrite rule I need to put in place in addition to the filter.

  2. Sebastien Couture
    Member
    Posted 3 years ago #

    bump

  3. Andy Macaulay-Brook
    Member
    Posted 3 years ago #

    Don't know if this is the cause, but your add_filter call specifies 3 parameters and your function only takes 2.

    If you look at the WordPress source, this filter takes 4 parameters.

    The docs for add_filter suggest that it does little or no error checking for performance reasons, so it might just be silently trying (& failing) to cope with the mismatch.

  4. jorgecosgayon
    Member
    Posted 3 years ago #

    Just rebuild your permalink structure from the dashboard - just hit the save changes button and your htaccess should be changed to recognize your new structure

  5. dashaluna
    Member
    Posted 3 years ago #

    @jorgecosgayon, thanks for that. I've spent a day and a bit trying to figure out why I was getting 404 after adding a rewrite rule in my register_post_type ... I just hit Save Changes button on the Perpalinks Settings screen and all works now.

  6. mighty_mt
    Member
    Posted 3 years ago #

    Just wanted to say that @jorgecosgayon's comment helped me as well.
    I went to the "Permalinks" Settings page and clicked "Save Changes" without changing anything and now my new custom post type seems to work perfectly.

Topic Closed

This topic has been closed to new replies.

About this Topic