WordPress and buddypress programming

restricted posts pages WordPress with short code

Viewing 0 reply threads
  • Author
    Posts
    • #2852
      Michael Mc
      Keymaster
      @mkmcst
      <?php
      add_action('init', 'wpse57819_add_shortcode');
      /**
       * Adds the shortcode
       *
       * @uses add_shortcode
       * @return null
       */
      function wpse57819_add_shortcode()
      {
          add_shortcode('restricted', 'wpse57819_shortcode_cb');
      }

      Then in your callback function, you can check to see if the user is logged in. If they are, show them the content. If not, show them a login message. You can do literally whatever you want here: check for user capabilities to show them the content (different “membership levels”), show them an entire login form. A simple example:

      <?php
      /**
       * Callback function for the shortcode.  Checks if a user is logged in.  If they
       * are, display the content.  If not, show them a link to the login form.
       *
       * @return string
       */
      function wpse57819_shortcode_cb($args, $content=null)
      {
          // if the user is logged in just show them the content.  You could check
          // rolls and capabilities here if you wanted as well
          if(is_user_logged_in())
              return $content;
      
          // If we're here, they aren't logged in, show them a message
          $defaults = array(
              // message show to non-logged in users
              'msg'    => __('You must login to see this content.', 'wpse57819'),
              // Login page link
              'link'   => site_url('wp-login.php'),
              // login link anchor text
              'anchor' => __('Login.', 'wpse57819')
          );
          $args = wp_parse_args($args, $defaults);
      
          $msg = sprintf(
              '<aside class="login-warning">%s <a href="%s">%s</a></aside>',
              esc_html($args['msg']),
              esc_url($args['link']),
              esc_html($args['anchor'])
          );
      
          return $msg;
      }

      Somewhere in your pages/posts:

      [restricted]
      Content for members only goes here
      [/restricted]

Viewing 0 reply threads
  • You must be logged in to reply to this topic.