{“content”: “\u003cdiv data-theme-toc="true"\u003e \u003c/div\u003e\n\nDiscourse tiene la capacidad de incrustar los comentarios de un tema en un sitio remoto utilizando una API de Javascript que crea un IFRAME. Para un ejemplo de esto en acción, consulta el blog de Coding Horror. El blog se ejecuta a través de Ghost pero los comentarios se incrustan desde su foro de Discourse.\n\nAlgo importante a tener en cuenta con esta configuración es que los usuarios deben navegar a tu foro para publicar respuestas. Esto es intencional, ya que creemos que la interfaz de publicación en un foro de Discourse es actualmente mucho más rica de lo que podríamos incrustar a través de Javascript.\n\nEsta guía te mostrará cómo configurar la incrustación de comentarios en tu propio blog o sitio web.\n\n### Cómo funciona\n\nEn Discourse, un tema se compone de muchas publicaciones. Cuando estás incrustando Discourse en otro sitio, estás vinculando un documento (entrada de blog, página HTML, etc.) con un único tema. Cuando las personas publican en ese tema, sus comentarios aparecerán automáticamente en la página donde lo incrustaste.\n\nTienes la opción de hacer que Discourse cree los temas automáticamente cuando se encuentre una nueva incrustación, o puedes crear los temas tú mismo con anticipación.\n\n### Configuración de Discourse para la incrustación (configuración simple)\n\nLa siguiente configuración incrustará un feed de comentarios en una página con la URL de un blog falso de http://example.com/blog/entry-123.html, desde un foro de Discourse que se ejecuta en =DISCOURSE=.\n\nDominio para \u0026nbsp;\nDominio para \u0026nbsp;\n\n1. Visita Admin \u0026gt; Personalizar \u0026gt; Incrustación en tu instalación de Discourse. https://=DISCOURSE=/admin/customize/embedding\n\n2. Crea al menos un Host Incrustable. Este debería ser el nombre de host (dominio) donde deseas incrustar tus comentarios. En este caso, el host es =BLOG= – ten en cuenta la ausencia de http:// y la ruta.\n\n - Lista de permisos de ruta te permite especificar las rutas en el host remoto que aceptarían tu incrustación.\n\n - Publicar en categoría - si proporcionas una categoría junto con el host que estás ingresando, las publicaciones importadas de ese host terminarán automáticamente en esa categoría. Diferentes hosts pueden publicar en diferentes categorías.\n\n - Etiquetas - puedes asignar etiquetas para que se apliquen automáticamente a los temas creados a partir de un host determinado.\n\n - Autor de la publicación - puedes anular opcionalmente el usuario creador del tema por host. Si no se establece, se utiliza el valor predeterminado de la pestaña Publicaciones y temas.\n \n3. Navega a la pestaña Publicaciones y temas y rellena el campo Nombre de usuario para la creación de temas. Este es el usuario que creará temas cuando se encuentren nuevas incrustaciones. Supongamos que nuestro discourse tiene un usuario llamado eviltrout, por lo que el valor es eviltrout.\n\n4. Inserta el siguiente HTML en la página web en http://=BLOG=/blog/entry-123.html\n\nhtml\n\u003cdiv id='discourse-comments'\u003e\u003c/div\u003e\n\n\u003cscript type=\"text/javascript\"\u003e\n DiscourseEmbed = {\n discourseUrl: 'https://discourse.example.com/',\n discourseEmbedUrl: 'http://example.com/blog/entry-123.html',\n // className: 'CLASS_NAME',\n };\n\n (function() {\n var d = document.createElement('script'); d.type = 'text/javascript'; d.async = true;\n d.src = DiscourseEmbed.discourseUrl + 'javascripts/embed.js';\n (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);\n })();\n\u003c/script\u003e\n\n\nLas partes configurables del fragmento están en el objeto DiscourseEmbed. discourseUrl es la ruta completa a la base de tu discourse, incluida la barra inclinada final. discourseEmbedUrl es el documento que actualmente incrusta un feed de comentarios.\n\nSi configuras esto correctamente, la primera vez que visites http://=BLOG=/blog/entry-123.html, intentará cargar comentarios para la publicación del blog. Como no hay ninguno, le indicará al foro de Discourse que cree un nuevo tema en segundo plano. eviltrout creará un nuevo tema y el contenido de la primera publicación se rastreará desde tu blog y el texto se extraerá automáticamente.\n\nUna vez que se crea el nuevo tema, los usuarios pueden publicar en él y sus comentarios se mostrarán automáticamente la próxima vez que se visite http://=BLOG=/blog/entry-123.html.\n\nclassName es opcional y agregará una clase de tu elección a la incrustación para que puedas personalizarla con CSS.\n\n\u003e
Consejo: Si tu blog tiene varios autores, puedes agregar una etiqueta \u003cmeta name=\"discourse-username\" content=\"author_username\"\u003e a cada página. Cuando Discourse rastree la página para crear el tema, utilizará esta etiqueta meta para determinar el autor de la publicación, anulando el nombre de usuario predeterminado establecido en la configuración de administración.\n\n### Incrustación en más de una página\n\nEn el ejemplo anterior codificamos nuestra URL http://=BLOG=/blog/entry-123.html al incrustar el fragmento de Javascript. Esto generalmente no será suficiente, ya que muchos sitios tienen muchas páginas que se generan automáticamente. Por ejemplo, en un blog, cada entrada normalmente tiene su propia página. Para admitir esto, coloca el mismo fragmento en cada página donde desees mostrar comentarios, pero reemplaza el valor pasado a discourseEmbedUrl con la URL de la página actual. En mi blog, utilizo el siguiente valor para discourseEmbedUrl: 'http://eviltrout.com\u003c%= current_page.url %\u003e' – a medida que se crean nuevas páginas de blog, se crearán nuevos temas para ellas automáticamente en Discourse.\n\n### Estilizando tu contenido incrustado\n\nTienes la capacidad de agregar una hoja de estilo para tus comentarios incrustados. Usa la sección CSS Incrustado del editor de temas en Admin \u003e Personalizar \u003e Temas \u003e [tu tema] \u003e Editar CSS/HTML y puedes agregar una hoja de estilo personalizada que se servirá con tus comentarios incrustados. Por defecto, pensamos que el diseño se ve bien en un fondo blanco, pero si tu sitio tiene un diseño único, querrás estilizarlo tú mismo.\n\n### (Opcional) Agregar un feed para sondeo\n\nComo se mencionó anteriormente, Discourse rastreará automáticamente cualquier sitio en el que esté incrustado. Sin embargo, a veces el HTML puede ser difícil de analizar y es posible que no extraiga el contenido de tus publicaciones correctamente. Muchos blogs y sitios web admiten feeds RSS/Atom para sindicación, y Discourse puede usar esto para extraer el contenido de tus publicaciones de blog con mayor precisión.\n\nDiscourse incluye el plugin de sondeo RSS (incluido por defecto). Si tienes configurado un feed RSS o Atom en el sitio en el que estás incrustando Discourse, puedes habilitar la configuración del sitio rss_polling_enabled y agregar la URL de tu feed a través de Admin \u003e Plugins \u003e Sondeo RSS. Una vez que se haya agregado la URL del feed, Discourse analizará el feed y publicará sus publicaciones en la categoría apropiada según los Hosts Permitidos que agregues a tu configuración de Incrustación.\n\n### (Configuración alternativa) Vinculación a temas existentes\n\nA algunas personas prefieren no hacer que Discourse cree temas automáticamente en sus foros. Les gustaría crear los temas ellos mismos y luego simplemente indicarle a su código de incrustación qué tema quieren asociar. Puedes hacer esto cambiando ligeramente tu código de incrustación:\n\nhtml\n\u003cdiv id='discourse-comments'\u003e\u003c/div\u003e\n\n\u003cscript type=\"text/javascript\"\u003e\n window.DiscourseEmbed = {\n discourseUrl: 'https://=DISCOURSE=/',\n topicId: 12345\n };\n\n (function() {\n var d = document.createElement('script'); d.type = 'text/javascript'; d.async = true;\n d.src = window.DiscourseEmbed.discourseUrl + 'javascripts/embed.js';\n (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(d);\n })();\n\u003c/script\u003e\n\n\nLa única diferencia aquí es que hemos reemplazado discourseEmbedUrl con el ID de un tema de Discourse. Si haces esto, no se creará ningún tema y los comentarios de ese tema se mostrarán automáticamente.\n\n### Establecer la política de remitente\n\nDebido a los recientes cambios (septiembre de 2020) en la política de remitente predeterminada que establecen muchos navegadores, Discourse ahora establece explícitamente la política de remitente del iframe en \"no-referrer-when-downgrade\". Si, por razones de seguridad, tu sitio requiere una política de remitente más estricta, se puede establecer agregando un valor discourseReferrerPolicy al objeto DiscourseEmbed del script de incrustación. Por ejemplo:\n\njs\nDiscourseEmbed = { discourseUrl: 'https://forum.example.com/',\n discourseEmbedUrl: '\u003cyour_posts_canonical_URL\u003e',\n discourseReferrerPolicy: 'strict-origin-when-cross-origin'};\n\n\n### Consulta programática de los detalles de la incrustación\n\nTeneos un endpoint de API para consultar los detalles de la incrustación utilizando la embed_url como parámetro:\n\n\ncurl 'https://meta.discourse.org/embed/info?embed_url=https://blog.discourse.org/2021/04/discourse-team-grows-to-50' -H 'API-KEY: logapikeygoeshere' -H 'API-USERNAME: apiusernamehere' \n\n\nY la respuesta es:\n\njson\n{\n \"topic_id\": 187794,\n \"post_id\": 925017,\n \"topic_slug\": \"discourse-team-grows-to-50-blog\",\n \"comment_count\": 2\n}\n\n\n### Incrustación de comentarios desde un sitio privado\n\nPara las instancias privadas de Discourse, si Discourse está en un subdominio del dominio del blog, los comentarios se mostrarán a los usuarios que hayan iniciado sesión en Discourse. Los usuarios que no hayan iniciado sesión en Discourse verán un mensaje de ‘se negó a conectarse’. Si Discourse y el blog están en dominios completamente separados, no se mostrarán comentarios para los foros privados.\n\n### Solución de problemas\n\nEl problema más común que tienen los usuarios al incrustar Discourse es establecer el valor correcto para los hosts incrustables que agregaron. Asegúrate de verificar dos veces que sea solo el dominio de tu sitio y que no contenga barras adicionales ni caracteres no válidos.”}
Is it possible to use this method if the Discourse category is hidden from public view?
Probably not, but it might work if all of your viewers are logged in.
I’ve created a tutorial that walks you through the process of setting up a local discourse instance on vagrant for your local tests to embed discourse in your front-end development project. You can find it here: Local discourse: vagrant, ansible, lxd, docker, discourse-embedding
This is different from other descriptions that I found before in that it allows you to run locally a complete discourse set-up like you would do in production to get a feel for the “real” set-up process. In addition this set-up is able to serve as a local development playground for embedding discourse into your project.
Hi, is there a way to disable embedding for posts in draft status? I can’t see any handlebar within Ghost for post status, can I change the embed settings to exclude /p/ which is used to preview posts? I have a problem where posts that are previewed are being added to Discourse. Cheers.
Can’t seem to find the setting to style the embedding iframe any more…? Is the original post out of date somehow?
EDIT: Nevermind, it had just changed places. I can add it to a theme component
thanks!
This sounds like a ghost question, not a Discourse question? However your Ghost integration is working needs to take that into account, not Discourse.
Hello everyone!
I need some help to embed Discourse into READTHEDOCS (using Sphinx)
Does anyone have this kind of experience?
Looks like there is GitHub - pdavide/sphinxcontrib-discourse which always embed a single topic.
Thank you for reply, let check it out
Hey Guys
I’ve been having some trouble embedding to a specific topic:
I’ve been trying different variations of settings and I still just get ‘Error Embedding’ On My Website.
Is it noticeable at all what I may be doing wrong? I’ve spent forever trying to get it to work, any help is appreciated.
Current Code Embedded On Website
Are there any errors in your Javascript console?
In your first screenshot, you have all the paths set to publish to the uncategorized category. If you want to publish all posts to the same category you only need to create one Embeddable host record.
The Path Whitelist values that you have added to your Host entries might be causing problems. You can leave that value blank to publish all posts from your blog site that you’ve added the Discourse embed script to. If you want to set a specific path to publish to a Discourse category, the path should end with /.*. For example /sites/.*
The double slash at the start of your /t/newsletter-discussions/105 path may be a problem. Also, that looks like the path to a Discourse topic. If set, the path should be the path to a grouping of posts on your blog. The purpose of the Path Whitelist setting is to allow you to publish posts from a specific path on your blog to a specific Discourse category.
Ok thank you Simon, I appreciate it. I will give this a shot.
Like @codinghorror, I also use this DIscourse integration with Ghost using the stock configuration which uses the absolute URL as the discourseEmbedURL.
A week or so ago, I decided to change my Ghost blog’s routing so that posts with URLs like https://engineerworkshop.com/2020/02/20/how-to-set-up-wireguard-on-a-raspberry-pi/ are redirected to https://engineerworkshop.com/blog/how-to-set-up-wireguard-on-a-raspberry-pi/, with https://engineerworkshop.com/blog/how-to-set-up-wireguard-on-a-raspberry-pi/ being the new permalink.
The Problem
You can probably anticipate the problem this creates: the discourseEmbedURL is set to the old URL and so when the embed script is called, which now has a different URL, a new comment post is created in Discourse.
Solution Attempt (Which Failed)
Now, prior to this, I had anticipated this problem, and so I thought I was being clever using a regex pattern with remap to fix the URLs: rake posts:remap["[0-9]{4}\/[0-9]{2}\/[0-9]{2}","blog",regex]
While that did “sort of” work, wherever the URL was used in the original Discourse comment post, sadly, when I loaded the blog posts, new comment topics were created in Discourse.
Ultimately, I just reloaded every post on my site and transferred comments from the old topics to my new topics, deleting the originals (I know, I know). Obviously killing pages is bad for SEO, not to mention end-user experience.
My Question
I assume the reason my regex patch attempt didn’t work is because the Discourse topic is somehow keyed to the URL on the backend. (I readily admit to being ignorant of Discourse’s data structure). For future knowledge, and anyone else that may attempt to do the same in the future, is there a way to remap a DIscourse topic to a new blog post URL?
Thanks in advance!
7 posts were merged into an existing topic: WP Discourse Embed Plugin
I love this feature as I have many magazine-style content sites and I can auto generate the topics into our forums but is there a way to get the URL preview working like it does normally in Discourse?
So instead of this:
More like this:
Thanks,
Jim
If you have the link on a separate line by itself it should Onebox.
Then have your entire description line below, including the link, as you show in your first image. That will appear below the Oneboxed link.
Hmm… well that’s a bit of a problem as the page itself is what is being previewed. So putting a link at the very top of the page HTML or article text is kinda problematic. Here is the page in question:
https://modelshipwrights.com/news/us-navy-light-cruiser-cl-89-miami
Hi folks. I’ve almost got this working, but realised that the use case I had in mind looks like it may not be as straightforward as I had hoped, and I am not sure how much additional work is involved.
I’m hoping to use this feature to power discussions on a site that is based around user generated content. I have no issues with the embedding of comments, or getting SSO set up and ensuring my users automatically become members of my community with the same emails, usernames, etc.
What I was hoping is that, when a new piece of user content is created on my site, that the user who published it becomes the author of the related Discourse post, not a single user as defined in the “Username for topic creation” setting of the embed feature. I won’t be allowing signups outside of my current signup process so I can be 100% sure that the Discourse user will already exist or, at least, can be created at that time we create the new thread.
Hopefully it’s obvious why I’d want to do this. ie. the content creator would then be the discussion’s OP on my Discourse site and could be automatically subscribed to the thread and notified of replies, their posts highlighted so as to stand out from other comments, etc, etc.
Any suggestions on where to start?
Thanks!



