I have a series of extra fields for my K2 items that I only want to show to logged in users. To add more complexity, I need to show one field to one User Group and a different field to a different User Group. How, can I accomplish this?
I know I can do access level checks for modules, but since these are extra fields attached to K2 items, I'm fumbling for a way to accomplish this.
I was able to accomplish this using the following code (in abbreviated form):
<?php $user = JFactory::getUser(); ?>
<?php if(!$user->guest): ?>
<!-- Prices -->
<div class="moduletable">
<h3 class="specs">Pricing</h3>
<?php
$none = true;
foreach ($this->item->extra_fields as $key=>$extraField) {
if($extraField->value && $extraField->name=='Price A' && in_array(25,$user->groups)) {
echo $extraField->value;
$none = false;
break;
}
elseif($extraField->value && $extraField->name=='Price B' && in_array(26,$user->groups)) {
echo $extraField->value;
$none = false;
break;
}
}
if ($none) echo '<br/><p>Coming Soon!</p>';
?>
</div>
<?php endif; ?>
Basically, I check to see if the user is logged in, then run through the extra fields to see if the field name is "Price A" and the user is in the user group "Price A" (ID=25). If it matches, I output the price and move on. If not, it does the same check for "Price B." If an extra field for price isn't assigned or the user doesn't have a price level, I give an encouraging message! ;)
Note: You must ensure all of your K2 templates within your theme which call the item extra fields have code to prevent these extra fields from displaying the content, or you risk showing the content to the public. This can include any of the PHP files in your com_k2/templates
folders where your K2 settings specify extra fields to be displayed, or where you've manually forced them to be displayed in your templates.