How can I add to shortcodes? - php

I have plugin A that needs to verify two pieces of shortcodes before an action takes place within another plugin.
<?php
function mepr_add_some_tabs($user) {
?>
<span class="mepr-nav-item prem-support <?php MeprAccountHelper::active_nav('member-profile'); ?>">
<!-- KEEPS THE USER ON THE ACCOUNT PAGE -->
Profile
</span>
<?php
}
add_action('mepr_account_nav', 'mepr_add_some_tabs');
function mepr_add_tabs_content($action) {
//Listens for the "member-profile" action on the account page, before rendering the FF view shortcode.
if($action == 'member-profile') {
echo do_shortcode('[frm-condition source=frm-stats id=80 type=count user_id=current greater_than=0] [display-frm-data id=5728] [/frm-condition]');
}
}
add_action('mepr_account_nav_content', 'mepr_add_tabs_content');
The problem is I'm not a developer and I don't know how to add the second shortcode in the echo do_shortcode function.
The current shortcode basically says: if the user has an entry on the field ID: 80, then show them the content of the entry.
What I need to add is another, second shortcode which will say almost the same thing, but about another field ID.
How can I add it while following this requirement?

Related

Wordpress query users and display as taxonomy

I have returned a list of registered users. I am looking to be able to query these results and also generate a click through page. Is that possible.
Im trying to essentially get a list of users by searching (first name for example), then click through to show information about them, on the front end. Its mainly the click through im having difficulty with.
For example if i could click a member and it would go through to a page that had the user first name, last name etc.
<?php
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
if ( in_array( 'team_member', (array) $user->roles ) ) {
?>
<div class="member_user">
<a href="<?php echo the_permalink();?>">
<?php
echo $user->first_name." ".$user->last_name;
?>
</a>
</div>
<?php
}
}
?>
If i understood correctly, you already have a list of users, and you want each one of them to be linkable to its own page, where you would display the info you want, such as first name, last name etc.
Firstly you have to query for your users and loop through them to display them in a list. You already have this in your code, but if you want something more advanced a query would look like this:
$authors = get_users(array(
'role__not_in' => array('Subscriber', 'Administrator'),
//if you do not want to list the admins and subscribers
'orderby' => array(
'post_count' => 'DESC',
//order users by post count (how many posts they have)
)
));
foreach ($authors as &$author){
//loop through the users
$user_info = get_userdata($author->ID);
$user_link = get_author_posts_url($author->ID);
?>
<a href="<?php echo $user_link; ?>" style="display:block;">
<?php echo $user_info->first_name.' '.$user_info->last_name; ?>
</a>
<?php
}
Then you need to create the page for the user. WordPress handles this by author.php page. If your theme does not have one, simple create a php file called author.php and place it at the root folder of your theme.
You may edit author.php to include the data you want. However if you remove the list of posts that are displayed by default for the selected user you will loose this functionality in your theme.
So inside author.php you may get the user like so:
//get current user (object):
$current_author = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
//get User data by user ID
$user_info = get_userdata($current_author->ID);
//echo first & last name:
echo $user_info->first_name.' '.$user_info->last_name;
If you make a print_r($user_info) you may see what info you can display for the selected user.
You may also use the 'get_the_author_meta' function to get more info from the user's profile, eg
get_the_author_meta('description', $current_author->ID);
You can find more info about this function here: https://developer.wordpress.org/reference/functions/get_the_author_meta/
I would generate a link like this:
<?php
echo $user->first_name." ".$user->last_name;
echo 'view user';
?>
And then query the user ID on the next page to get the desired information.
On the next page you can:
<?php
$user_ID = $_GET['user_id'];
get_header();
?>
and then query this to get pretty much any content related to that user
Two and a half approaches:
You could customize your theme's author archive template to display the desired information. Three author archives are available in the template hierarchy:
author-{nicename}.php
author-{id}.php
author.php
You'd be able to link to https://{site_url}/author/{username} for each user.
However, this may not be ideal if you want to keep that normal author blog archive and add the new profile pages. So what may be better long term is to setup a custom post type for the member profiles, then every time a new "member" user is created run a function that creates a new post representing the user.
You can register that custom post type manually with register_post_type() or if you need help a good plugin is Custom Post Type UI.
A good action for your function to hook into is user_register since it happens immediately after user registration but will have access to user data. Within your function you can create the new post using wp_insert_post().
You can then display the information of that custom post type using the archive-$posttype.php and single-$posttype.php templates.
2 1/2. You may also consider using only the custom post type and not querying for users at all. If this member profile is the only reason some folks are users it may even be more convenient this way. Then you can use the archive-$posttype.php and single-$posttype.php templates easily to display the information you choose.
There is a function for that. Use get_author_posts_url()
In the required template use the following code:
// only return required user based on role
$args = array(
'role' => 'team_member'
);
$blogusers = get_users( $args );
// loop though and create output
foreach ( $blogusers as $user ) : ?>
<div class="member_user">
<a href="<?php echo get_author_posts_url( $user->ID );?>"> // links to author page
<?php echo $user->first_name." ".$user->last_name; ?>
</a>
</div>
<?php endforeach;
You will then need to customise the author.php template in your theme to render as required.

How do you check the category of the next/previous post?

I'm working on a wordpress site with several categories, where each of those categories have posts. Example: I have "Work" and "Careers" as two categories.
When you click on a "Work" post, at the top of the page there is a "Previous / Next" button to display the next or previous post with the category "Work". Right now, the code is set up like this:
<div class="campaign__previous l-campaign__previous">
<?php previous_post_link('%link','Previous Campaign', TRUE); ?>
</div>
<span>/</span>
<div class="campaign__next l-campaign__next">
<?php next_post_link('%link','Next Campaign', TRUE); ?>
</div>
The wordpress function next_post_link('%link','LINK TEXT', TRUE) automatically doesn't display the link if there are no more posts in that category. That's great, but I also want to not display the
<span>/</span>
if there are no more posts in that category. How do I check this myself? I have tried:
if( next_post_link('%link','Next Campaign', TRUE) ) {
echo '<span>/</span>';
}
This did not work. Any ideas?
For WordPress functions that print something to the screen automatically, there is usually a version with the prefix get_ that will simply return the value. I don't have the ability to test this now but I assume the following might work or at least get you close:
if( get_next_post_link('%link','Next Campaign', TRUE) == "" )
// No More
else
// More to Come
Now there definitely seems like there is a better way to do this but this was just the first thing I thought of when I read your code.
https://developer.wordpress.org/reference/functions/get_next_post_link/

Potential Security Issues with Passing Wordpress Variable as a Parameter on get_permalink()

I need to make sure I'm not opening up a security hole in my site. I have a Custom Post Type called "Communities" and a custom post type called "Floor Plans" and need to add a parameter to the URL on Single Floorplan posts.
My goal is that when a Floorplan post object is selected from a Communities Single post, it appends the name of the community (i.e. single community post title) to the URL for use on the following page. So, enabling query vars:
<?php
//* Enable queryvars (functions.php)
add_filter('query_vars', 'parameter_queryvars' );
function parameter_queryvars( $qvars )
{
$qvars[] = "community";
return $qvars;
}
I have a template part called "dynamic-floor-plans" that lives in a loop at the bottom of Single Communities posts. I'm grabbing the single_post_title of the current communities page, and passing that to the URL so that it's available using $_GET
The reason we opted for this method is that the "Floor Plans" post type has a canonical/default version that has the same properties as its Community-specific counterparts. In order to avoid a post relationship situation (which would give the user flat out wrong data in some cases) the community versions just have to be able to use
<?php
//* dynamic-floor-plans template part (placed in loop on communities page)
global $post;
$string = strtolower(single_post_title( null, false ));
$slug = str_replace(' ','-',$string);
?>
<div class="card-button">
<a class="small expanded secondary button"
href="<?php echo get_the_permalink() . '?community=' . $slug ?>">View Floorplan</a>
</div>
Now, this totally is working. I'm able to grab that community variable on the subsequently-selected floorplan single page using $_GET and things seem to be working nicely on the front end:
<?php
//* Single Floorplans Template
$community = $_GET["community"];
?>
<h1 class="entry-title"><?php echo $title ?></h1>
<h4>
<?php if ($community) { ?>
At <?php echo $community; } ?>
</h4>
...
I just can't help but feel that this isn't kosher, or that there's a more secure way to do this.
Am I open to exploitation? I can include the function for the loop itself as well, but figure this code will be sufficient to get started in evaluation.

Hide php code if?

What I want to do is really simple but I'm obviously not great and very new to PHP. I'm using woocommerce for my store and a woocommerce add on called "woocommerce scheduler" to set a start and end time specific products are for sale each day.
The way the scheduling program works is you set start and end times with 24hr clock example 10am (10:00) to 8pm (20:00) the product can be purchased anytime from 8am-10pm after 10pm the plugin "hides" the add to cart button ans displays a custom message such as "Currently Unavailable" and you can't purchase the item.
I ran into 2 problems one of which is solved
I wanted the plugin to show the start time the product would become available with the unavailable message basically it would say "unavailable until 8am"
So the solution to that problem was a plugin called Advanced Custom Fields
and creating a custom field that I can set on the product page and then I can display by putting this php code if the feild is empty on another product page it isn't displayed <?php if( get_field('product_time') ): ?>
<p>Available at <?php the_field('product_time'); ?></p>
<?php endif; ?>
into my single product page template file.
I got that working just fine. Now my second issue that I can't solve.
I want to hide the code that shows the time when the unavailable message is hidden because the product is in the hours where it is available for purchase. So how would I go about this?
I found the bit of code that pulls the unavailable message but it is a js. file so I cant put the php I have into that file.
wdm_validate.js
jQuery(document).ready(function(){
jQuery('.cart').html('<p class = "wdm_message3">'+wdm_message.wdm_expiration_message+' </p>');
});
this is the bit in the php file for the scheduler plugin that calls that js file
woocommerce_scheduler.php
if($wdm_start_date <= $d && $d<=$wdm_end_date && $str_start_time <=
$curtime && $curtime <= $str_end_time) {
}else{
//echo "<style>.cart{display:none;}</style>";
//echo "hello";
//exit;
wp_enqueue_script('wdm_expiration_message',plugins_url('js/wdm_validate.js',__FILE__),
array('jquery'));
$data = array(
'wdm_expiration_message' => get_option( 'woocommerce_custom_product_expiration',true )
);
wp_localize_script('wdm_expiration_message','wdm_message',$data);
}
In your custom code just add class to <p> tag and perform following:-
<?php if( get_field('product_time') ): ?>
<p class='wdm_available'>Available at <?php the_field('product_time'); ?></p>
<script>
jQuery(document).ready(function(){
//checking wdm_message3 i.e. expiration message exist or not
if(!jQuery('.wdm_message3').is(':visible')){
jQuery('.wdm_available').hide();
}
});
</script>
<?php endif; ?>
adding this code to my price.php template page in woocommerce got me exactly what I needed. The time is hidden when the product is available and shows when the item is not available for sale letting my customer know what time they can purchase it.
<?php if( get_field('product_time') ): ?>
<p class='wdm_available'>Unavailable Until <?php the_field('product_time'); ?></p>
<script>
jQuery(document).ready(function(){
// set a timeout function to get around brief delay in scheduler script
setTimeout(function(){
//check if scheduler message is NOT visible
if(!jQuery('.wdm_message3').is(':visible')) {
// if not, hide custom availabilty time message
jQuery('.wdm_available').hide();
}
}, 0);
});
</script>
<?php endif; ?>
There's no way for me to know the format of your custom field, but you should be able to run a comparison against the current time. As an idea:
$current_time = time();
$sale_time = get_field('product_time');
if( $sale_time && $sale_time < $current_time ): ?>
<p class='wdm_available'>Unavailable Until <?php the_field('product_time'); ?></p>
<?php endif; ?>

Using Advanced Custom Fields and Contact Form 7 to display a form

I want my users to be able to put a Contact Form 7 shortcode into a custom field in the Wordpress editor. I've created the custom field using ACF and I can pull the value onto the page, but when I try to include it in the shortcode, it comes back with a 404.
This code:
<?php echo do_shortcode(get_field('contact_form_shortcode')); ?>
Returns:
[contact-form-7 404 "Not Found"]
If I create a variable out of the value like this:
<?php
$formCode = get_field('contact_form_shortcode');
echo $formCode;
?>
The echo returns:
[contact-form-7 id="473" title="Learn More Form"]
But I get the same 404 after putting that value into the echo do_shortcode function list this:
<?php echo do_shortcode($formCode); ?>
What am I missing?
To do it With ACF pro plugin and without other extra plugins.
Create a relation field ( example: contact_form )
add the below code into your page loop:
<?php $posts = get_field('contact_form');
if( $posts ):
foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT)
$cf7_id= $p->ID;
echo do_shortcode( '[contact-form-7 id="'.$cf7_id.'" ]' );
endforeach;
endif; ?>
I was able to resolve this issue by using the technique I discussed in my comment above. By using the WYSWIG field set to 'Run filter "the_content"' I'm able to pull the field value in the way I want it. The only drawback is that users could type something else in there besides a form shortcode.
Here's my final code:
<?php
if (get_field('contact_form_shortcode')):
echo get_field('contact_form_shortcode');
else:
echo do_shortcode('[contact-form-7 id="473" title="Learn More Form"]');
endif;
?>
Instead of using a WYSIWYG field, you can simply set a Text field to "Convert HTML into tags" under the Formatting setting on the field. This will stop the 404 errors from CF7 and properly process the form. The WYSIWYG fields tend to be too hard to control from bad user input.
Here's my solution:
Create a "Post Object" type Field which will returns the post ID.
the Filter by Post Type for this field should be sett to "Contact Form" and Filter by Taxonomy leave empty.
Then in page template: (php)
<?php $contact_form = get_field('contact_form'); ?>
HTML:
<div class="col-12 col-md-8 offset-md-2">
<?php echo do_shortcode('[contact-form-7 id="'. $contact_form .'"]'); ?>
</div>
acf field screenshot
Another Solution :
1) Install https://github.com/taylormsj/acf-cf7
Installation
> 1 Copy the acf-cf7 folder into your wp-content/plugins folder
> 2 Activate the Contact Form 7 plugin via the plugins admin page
> 3 Create a new field via ACF and select the Contact Form 7 type
> 4 Please refer to the description for more info regarding the field type settings
2) Insert following code into template :
<?php if( get_field('field_acf') ):
the_field('field_acf');
endif; ?>
This applies to create a contact form 7 in a modal or Pop Up, multiple forms on the same page.
To paste CF7 shortcode (or any other generated shortcode) into ACF field as you were asking, just use the #armadadrive solution, which is exactly what question was about and it works.
create ACF text field with some name, eg hero_form
paste your shortcode into it
display contents like so <?php echo do_shortcode(get_field('hero_form')); ?>
Thanks #armadadrive
Here you can try please check the code for the shortcode below:
<?php echo do_shortcode(get_field('YourACFfieldNameHere')); ?>
I tried it on my website and it works.

Categories