0

I am looking for a way to hide the content of an AFC (advanced custom field) on the front-end until the user clicks a "Show" Button.

I don't want to use CSS (display:none) approach. The ACF content should not appear on the source code of the page, it should only be loaded after the user clicks.

How can i achieve this?

1 Answer 1

2

You're going to need to $.ajax() the contents of the field(s) on a click.

In a nutshell:

In your page template

<?php
global $post;
$post_id = $post->ID;
?>
<button class="acf-get-content-button">Let's see that content</button>
<div id="acf-content-wrapper" data-id="<?php echo $post_id; ?>"></div>

JS

(function($) {
  $('.acf-get-content-button').click(function(e){
    e.preventDefault();
    var $contentWrapper = $( '#acf-content-wrapper' );
    var postId = $contentWrapper.data( 'id' );

    $.ajax({
      url: "/wp-content/plugins/my-custom-plugin/public/field-ajax.php",
      type: "POST",
      data: {
        'post_id': postId
      },
    })
      .done(function( data ) {
        $contentWrapper.append( data );
      });
  });
})(jQuery);

field-ajax.php

<?php
define('WP_USE_THEMES', false);
require_once('../../../../wp-load.php');

$post_id = $_POST["post_id"];
$content = get_field( 'field', $post_id );

echo $content;

This code will need customization for your use, so it'll take some more research on your part.

Note that I placed the ajax script inside a custom plugin. This is what I would recommend, but some security plugins (iThemes Security, at least) has the option to disable running PHP in the plugins folder, which would break this.

8
  • Hmm i am not sure this is what i was trying to do. The admin will put information on a wysiwig field on the back end editor and publish the post. Then the visitors will need to click a button to see it. Is this what this does? Feb 7, 2017 at 22:10
  • That's not what this does, but it's the same idea. I'll change some things.
    – pants
    Feb 7, 2017 at 22:20
  • Ok, updated to retrieve a field value.
    – pants
    Feb 7, 2017 at 22:36
  • Ok i will try to implement this tomorrow and get back to you thanks! Feb 8, 2017 at 0:15
  • Hm trying to do this gives me "HTTP ERROR 500". I am trying to hide just the get_field('download') not the entire page not sure if this does that. Where exactly the JS part has to be in the template? I put it below the acf-get-content-button Feb 8, 2017 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.