Search code examples
phpwordpressadvanced-custom-fields

Showing private content to signed in clients on wordpress


I am currently trying to set up a client dashboard at my site, which is supposed to act as a sort of archive for all the documents exchanged such as invoices, design proposals, prototypes, etc. I added the files using ACF and mapped it to a user using the "user" field in ACF, but instead of showing them on a site anybody can access by knowing the URL, I need a private site for logged in users.

I created a child theme to the theme Astra in order to edit the php files. I have then created my own file and made that a template to be used when creating pages in the wp admin using the code:

<?php /* Template Name: Kundenbereich */ ?>

I've then created that template with some html and css and used php to pull data such as the name of the logged in user, which works just fine:

<h1>
Willkommen,
<?php
global $current_user;
wp_get_current_user() ;
echo $current_user->display_name;
?>!
</h1>

My plan was then to add the page created with this template as the account page in the plugin UsersWP, which locks it from anybody else, so only the logged-in user can view it. I suspected this step of breaking the code, so I tried it on a page that's not added to UsersWP and still, all ACF php functions break. The idea is that ACF checks who is logged in and then pulls the files from the set of data which has the corresponding user set in the "user" field.

This is the code that does not work:

<?php $current_user_id = get_current_user_id(); ?>
<p>
<?php the_field('kundenname', 'user_' . $current_user_id); ?>
</p>

<?php if( get_field('angebot', 'user_' . $current_user_id) ): ?>
<a href="<?php the_field('angebot', 'user_' . $current_user_id); ?>" >Herunterladen</a>
<? else: ?>
<a href="#" >Nicht verfügbar</a>
<?php endif; ?>

The user I tried it with has an ID of 1, but even changing the code to <?php the_field('kundenname', 'user_1'); ?> has done nothing and I don't know why.

All of the above works when I use a permalink and don't try checking for the user ID. But that's not private at all, therefore it won't work for me.

Is there a solution to this? Or perhaps a more elegant solution utilising only one plug-in?


Solution

  • I've realized my error, I used CPT UI to create a menu solely for the ACF fields, but all I needed to do was add the fields to the Wordpress user settings in the admin.

    This way my code above works, so if anybody needs a client dashboard, feel free to use it.

    Here's a quick screen share: https://www.loom.com/share/aab482dc0a05412b98d1529ee0ddcba5