#188 - Show/hide content based on a plan instead of gated content v0.1

Show or hide content dynamically based on your member's current subscription plan tier.

Ver demostración


<!-- 💙 MEMBERSCRIPT #188 v0.1 - SHOW/HIDE CONTENT BASED ON PLAN 💙 -->
<script>
(function() {
  'use strict';
  
  document.addEventListener("DOMContentLoaded", async function() {
    try {
      // Check if Memberstack is loaded
      if (!window.$memberstackDom) {
        console.error('MemberScript #188: Memberstack DOM package is not loaded.');
        return;
      }
      
      const memberstack = window.$memberstackDom;
      
      // Wait for Memberstack to be ready
      await waitForMemberstack();
      
      // Get current member
      const { data: member } = await memberstack.getCurrentMember();
      
      // If no member is logged in, remove all plan-specific content
      if (!member) {
        removeAllPlanContent();
        return;
      }
      
      // Get the current plan connection
      let planConnections = null;
      
      if (member.planConnections) {
        planConnections = member.planConnections;
      } else if (member.data && member.data.planConnections) {
        planConnections = member.data.planConnections;
      } else if (member.plans) {
        planConnections = member.plans;
      }
      
      // If no plan connections, remove all plan-specific content
      if (!planConnections || planConnections.length === 0) {
        removeAllPlanContent();
        return;
      }
      
      // Get the current plan ID from the most recent active plan
      const currentPlanConnection = planConnections[0];
      const currentPlanId = currentPlanConnection?.planId;
      const currentPriceId = currentPlanConnection?.payment?.priceId;
      
      // Collect all possible IDs to match against
      const matchingIds = [];
      if (currentPlanId) matchingIds.push(currentPlanId);
      if (currentPriceId) matchingIds.push(currentPriceId);
      
      if (matchingIds.length === 0) {
        removeAllPlanContent();
        return;
      }
      
      // Show/remove content based on plan/price IDs
      showPlanSpecificContent(matchingIds);
      
    } catch (error) {
      console.error('MemberScript #188: Error showing/hiding plan content:', error);
      // On error, remove all plan-specific content for security
      removeAllPlanContent();
    }
  });
  
  function waitForMemberstack() {
    return new Promise((resolve) => {
      if (window.$memberstackDom && window.$memberstackReady) {
        resolve();
      } else {
        document.addEventListener('memberstack.ready', resolve);
        // Fallback timeout
        setTimeout(resolve, 2000);
      }
    });
  }
  
  function showPlanSpecificContent(matchingIds) {
    // Find all elements with data-ms-code attributes (plan-specific content)
    const allPlanElements = document.querySelectorAll('[data-ms-code]');
    
    allPlanElements.forEach(element => {
      const elementPlanId = element.getAttribute('data-ms-code');
      
      // Check if element's plan ID matches any of the member's IDs (planId or priceId)
      const shouldShow = matchingIds.includes(elementPlanId);
      
      if (shouldShow) {
        element.classList.remove('ms-plan-hidden');
        element.classList.add('ms-plan-visible');
      } else {
        element.remove();
      }
    });
    
    if (allPlanElements.length === 0) {
      console.warn('MemberScript #188: No elements with data-ms-code attributes found. Add data-ms-code="PLAN_ID" to elements you want to show/hide based on plan.');
    }
  }
  
  function removeAllPlanContent() {
    // Completely remove all elements with data-ms-code attributes if no member is logged in
    const allPlanElements = document.querySelectorAll('[data-ms-code]');
    allPlanElements.forEach(element => {
      element.remove();
    });
  }
})();
</script>

Customer Showcase

Have you used a Memberscript in your project? We’d love to highlight your work and share it with the community!

Creación del escenario Make.com

1. Descargue el proyecto JSON a continuación para empezar.

2. Navegue hasta Make.com y Cree un nuevo escenario...

3. Haga clic en el pequeño cuadro con 3 puntos y luego Importar Blueprint...

4. Sube tu archivo y ¡voilá! Ya está listo para vincular sus propias cuentas.

¿Necesitas ayuda con este MemberScript?

Todos los clientes de Memberstack pueden solicitar asistencia en el Slack 2.0. Tenga en cuenta que no se trata de funciones oficiales y que no se puede garantizar la asistencia.

Únete al Slack 2.0
Notas de la versión
Atributos
Descripción
Atributo
No se han encontrado artículos.
Guías / Tutoriales
No se han encontrado artículos.
Tutorial
¿Qué es Memberstack?

Autenticación y pagos para sitios Webflow

Añada inicios de sesión, suscripciones, contenido cerrado y mucho más a su sitio Webflow: fácil y totalmente personalizable.

Más información

"Hemos estado utilizando Memberstack durante mucho tiempo, y nos ha ayudado a lograr cosas que nunca hubiéramos creído posible usando Webflow. Nos ha permitido construir plataformas con gran profundidad y funcionalidad y el equipo que hay detrás siempre ha sido súper servicial y receptivo a los comentarios"

Jamie Debnam
39 Digital

"He estado construyendo un sitio de membresía con Memberstack y Jetboost para un cliente. Se siente como magia construir con estas herramientas. Como alguien que ha trabajado en una agencia donde algunas de estas aplicaciones fueron codificadas desde cero, finalmente entiendo el bombo ahora. Esto es mucho más rápido y mucho más barato."

Félix Meens
Estudio Webflix

"Uno de los mejores productos para iniciar un sitio de membresía - Me gusta la facilidad de uso de Memberstack. Yo era capaz de mi sitio de membresía en marcha y funcionando dentro de un día. No hay nada más fácil que eso. También proporciona la funcionalidad que necesito para hacer la experiencia del usuario más personalizada."

Eric McQuesten
Nerds de la tecnología sanitaria
Depósito Off World

"Mi negocio no sería lo que es sin Memberstack. Si crees que 30 $/mes es caro, prueba a contratar a un desarrollador para que integre recomendaciones personalizadas en tu sitio por ese precio. Increíblemente flexible conjunto de herramientas para aquellos dispuestos a poner en algunos esfuerzos mínimos para ver su documentación bien elaborado."

Riley Brown
Depósito Off World

"La comunidad de Slack es una de las más activas que he visto y los clientes están dispuestos a responder preguntas y ofrecer soluciones. He realizado evaluaciones en profundidad de herramientas alternativas y siempre volvemos a Memberstack: ahórrate el tiempo y dale una oportunidad"."

Abadía Burtis
Nerds de la tecnología sanitaria
Slack

¿Necesitas ayuda con este MemberScript? ¡Únete a nuestra comunidad Slack!

Únete al Slack de la comunidad Memberstack y ¡pregunta! Espera una respuesta rápida de un miembro del equipo, un experto de Memberstack o un compañero de la comunidad.

Únete a nuestro Slack