How to override product_url in Spree 2.x / Rails 4 to make more SEO friendly?

时光怂恿深爱的人放手 提交于 2019-12-21 17:52:30

问题


I would like my product urls to look like:

/product-name-here/p

instead of:

/product/product-name-here

How can I achieve this?


回答1:


After a lot of research I figured it out.

There are two steps in this process. The first is to create a route that matches the new product route.

So go into your routes.rb and in this section:

mount Spree::Core::Engine, :at => '/' 
 # Spree Specific routes here
end

Add this line: get ':id/p' => 'spree/products#show'

So now it looks like this:

mount Spree::Core::Engine, :at => '/' 
 # Spree Specific routes here
 get ':id/p' => 'spree/products#show'
end

At this point you should be able to visit the product page with the new url structure: /product-name-here/p

Problem now is that all of links automatically generated by spree to product pages will still use the old URL structure, so we must fix that as well. To do this we're going to create an over-ride for the product_path function that spree uses to generate these urls. Create a new directory in your helpers folder called "spree" and then a new file inside that directory called products_helper.rb

Now in this file app/helpers/spree/products_helper.rb add the following code:

module Spree::ProductsHelper

  def product_path(product)
    "/#{product.permalink}/p"
  end

end

And that's it. Now all of the links spree generates will use that new URL structure. You can modify this guide to make whatever url structure you want within spree for your products.


Troubleshooting tip:

Not sure why, but after I created the ProductsHelper I was getting an error when I went to the cart about an undefined function: line_item_description_text

I don't use the normal spree descriptions in my cart, so to fix this I just added:

def line_item_description_text (var)
  ""
end


来源:https://stackoverflow.com/questions/23265528/how-to-override-product-url-in-spree-2-x-rails-4-to-make-more-seo-friendly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!