Multiple Facebook, Twitter share buttons in one page with custom image and title

后端 未结 3 1225
不知归路
不知归路 2021-02-06 06:31

I\'m creating a blog where the landing page will show 5 latest posts by default and each post will have a Facebook and Twitter share buttons on them.

I will need each of

3条回答
  •  囚心锁ツ
    2021-02-06 07:12

    I want to share a different solution i made for my Rails Application that i hope can help others to develop the same thing in their framework.

    I've build my application front-end in Angular - one-page app - so it can change to different content with each of its own share button with different image, description, and title without reloading.

    But because of this i had the same trouble with the share button data as well.

    The solution i found was to look for the request headers and check if they are coming from Facebook. If this is true, then render a different view only with a head tag with the corresponding content meta data Facebook reads.

    Controller and custom view with meta-data for each content:


    #works_controller.rb
      def index
        ...
        agent = request.headers["HTTP_USER_AGENT"].downcase
        if agent.include?("facebook")
          render_facebook_share_info @current_work, params
          return
        end
        ...
      end
    

    Then i set the variables

      def render_facebook_share_info work, params_passed
        @currentUrl = URL + "/themes/#{params_passed[:theme_id]}/works/#{params_passed[:work_id]}"
        @currentImage = work.share_image.present? ? work.share_image.url : work.cover_image.url 
        @currentTitle = work.title 
        description = work.share_description.present? ? work.share_description : "" 
        @currentDescription = description
        render 'shared_facebook_data', layout: false 
      end
    

    And then i render the variables in the view:

    
    
      
      
      
      
      
      
    
    

    Dynamic link for each content

    So now i can use a link with the work id for @current_work in the facebook.com/sharer.php URL, and Facebook will be triggered into 'thinking' it has its own page with its own meta-data.

    Mine was (in Angular):

    Share on Facebook
    

    Hope it helps someone - it worked for me.

提交回复
热议问题