Redirect to parent post after editing Repeatable Field Group (RFG) in Forms

In this example, we have a repeatable field group (RFG) assigned to some custom post type. On the single post page, we are showing a View of the RFG related to the current post. We want to give some Users the ability to edit those RFGs on the front-end using Forms. In the current system, the recommended approach is to use an Edit Post link in the View to send the User to a page containing a Form. This can be a tedious workflow if you must edit multiple RFGs, going back and forth from the parent post to the Form editor. This code snippet can be used to automatically redirect the User to the post containing the RFG, saving one step in the process. Note that you must set the Form to redirect to some existing Page in the Form configurations. Otherwise, the redirect code will not have any effect on the Form.

/* ----------------------------------------------------------------------- */
// REDIRECT TO RFG PARENT POST AFTER EDITING RFG IN FORMS
// After submitting edit RFG Form, redirect to the post containing the RFG
// Be sure to set some redirect in wp-admin for this Form
//
add_filter('cred_success_redirect', 'custom_redirect_rfg_editor',10,3);
function custom_redirect_rfg_editor($url, $post_id, $form_data)
{
  $forms = array( 12345 );
  $rfg_slug = 'your-rfg-slug';
  if ( in_array( $form_data['id'], $forms ) ) {
    $parent_id = toolset_get_related_post( $post_id, $rfg_slug );
    return get_permalink($parent_id);
  }
  return $url;
}

Bring back old Toolset Menu, and have Layouts Edit Button as well if layouts is assigned to content

The Toolset Menu in the Front End WP Admin Bar, if Layouts is assigend to the content, becomes leads to the Front End Editor of layouts.
You cannot access other Toolset items with it anymore.

Often Clients have nested Views and to quickly access them, the old menu was perfect.
The new way will introduce a lot of time wasted clicking around in the admin.

To those clients we can provide a filter that brings back the old Toolset Menu.

It is also very useful for debugging.

add_filter('toolset_filter_toolset_admin_bar_menu_disable', 'my_layout_menu');
function my_layout_menu(){
	return false;
}

Customise permitted image file types in CRED form

By default a Types image custom field added to a CRED form will accept the following file types to upload:

bmp|gif|ico|jpeg|jpg|png|svg|webp

When the form markup is printed the data-attribute used to declare the list of allowable extensions passes through a filter which can be used to modify it, provided you have the CRED form id, which in the example code is 107.

Add the following to functions.php

add_filter('wptoolset_forms_field_js_validation_data_cred_form_107_1', 'set_image_types', 99, 1);
function set_image_types( $params ) {

	if ( isset($params['extension']) ) {

		$params['extension']['args'][0] = "jpeg|jpg|png";
		$params['extension']['message'] = "You can only add jpeg, jpg, or png images";
	}
	return $params;
}

You can customise the list of allowed file extensions, and the message.

Note that you may run into issues if you try to add a file extension which WordPress itself restricts (not tested).

Removing duplicated posts based in a given custom field

add_filter('wpv_filter_query_post_process', 'get_distinct_by_custom_field', 99, 2);
function get_distinct_by_custom_field($query, $settings){

	if($settings['view_id'] == 25){

		$array = array();

		//Adding the custom field to the objects
		foreach ($query->posts as $key => $value) {
			$query->posts[$key]->custom_field = get_post_meta($value->ID, 'wpcf-my-custom-field', true);
			$array[] = (array) $query->posts[$key];
			unset($query->posts[$key]);
		}

		$array_tmp = array();

		//Removing duplicated property values for custom_field
		foreach ($array as $key => $value) {
			$array_tmp[$value['custom_field']] = $value;
		}

		$array = array_reverse($array_tmp);

		//Applying the new set of post objects (unique ones)
		foreach ($array as $key => $value) {
			$query->posts[$key] = (object) $value;
		}
	}

	return $query;
}

 

Display only parent items of the current user in CRED parent picker

By default CRED parent Picker lets you choose from all available parent Posts.
This snippet lets you populate the picker with only the parent posts of the current logged in user

This is how the CRED parent Picker field HTML has to look:

<div class="cred-group cred-group-parents">
  <div class="cred-field cred-field-_wpcf_belongs_page_id">//change "page" to your parent post slug
    <label class="cred-label">
      Choose Parent
    </label>
    <input type="hidden" id="parents_id" value="[get-parents]" /> This is only for test display: [get-parents]
      [cred_field field='_wpcf_belongs_page_id' value='']//change "page" to your Parent Post Slug
  </div>
</div>

This is the JS that has to be inserted to the CRED JS Editor

jQuery('document').ready(function(){
   
var post_parents = jQuery('#parents_id').val();
   
var arr = post_parents.split(',');
     
  jQuery("[name=_wpcf_belongs_page_id] > option").each(function() { //change "page" to your parent post slug
       
    var option_val = jQuery(this).val();
       
     if( jQuery.inArray(option_val, arr) == -1 && option_val != -1 ){
       jQuery(this).remove();
     }
  });
     
});

And this is the function to put into functions.php of your Theme

function get_parents($atts) {
    global $current_user;
    get_currentuserinfo();
    $author_query = array('post_type' => 'page', 'posts_per_page' => '-1','author' => $current_user->ID,); //change page to your parent post slug 
    $author_posts = new WP_Query($author_query);
    $parent_ids = "";
    while($author_posts->have_posts()) : $author_posts->the_post();
        $parent_ids .= get_the_ID() .",";
    endwhile;
   
    return $parent_ids;
}
add_shortcode('get-parents', 'get_parents');

It is recommended to use Views with this and register the ShortCode in Views > Compatibility

How to set a Access group to a post which is submitted by CRED

The Post stores the Access Custom Group as a meta field (custom post field)

You can update your Post using WordPress and CRED API, by addressing the hidden Custom Field Key:

_wpcf_access_group
The Value is the name you gave to the group, prefixed with

wpcf-custom-group-

So you can use a cred_save_data action, with update_post_meta

Apply this code on the CRED you are using and every new posts will have the proper (coded by you) Access group stored.

add_action('cred_save_data', 'my_save_data_action',10,2);
 
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==91)//Change to your CRED Form ID you use
    {
        $user = wp_get_current_user(); //We get the current user data
         
         if ( in_array( 'administrator', (array) $user->roles ) ) { //My example checks for admins. You can use any Custom Role as well here
           update_post_meta($post_id,'_wpcf_access_group','wpcf-custom-group-1584797355f2d242ba5c8c879e748829');//We update the metafield for the post created, and pass the correct Access Group ID. This is the value you need to find in the database.
        }
        else {//something else if above is not true
            update_post_meta($post_id,'_wpcf_access_group','wpcf-custom-group-a269970820bacb6c0384851664dbac44');
        }
    }
}

 

Relevant Documentation:
https://codex.wordpress.org/Function_Reference/update_post_meta

https://wp-types.com/documentation/user-guides/cred-api/#csd

https://wp-types.com/forums/topic/how-to-use-cred-post-form-to-set-post-group-for-new-cpt-post/#post-572829

Evaluate if product is bought by user

This shortcode evaluates if a certain (logged in) user has bought a certain (current in loop) product. The WooCommerce function seems buggy and some attention is needed. Check the code first to see if it is still working with the workaround.

functions.php:

add_shortcode('wpv-product-purchased', 'wpv_product_purchased_func');
  
function wpv_product_purchased_func($atts){
$current_user = wp_get_current_user();
$email = $current_user->email;
return (wc_customer_bought_product( $email, $current_user->ID, get_the_ID()));
}

Register this shortcode in Views > Settings:

wpv-product-purchased

Then evaluated as this:

 

 

The function of WooCommerce itself is returning a error, and the ShortCode works as expected, although it returns a numerical value “1” for bought and a empty value “” for not bought, not a boolean “true” or “false” as stated by WooCommerce.

This might be a Bug in their code or misunderstanding on my end reading the Core code of WooCommerce, and it could therefore change in future.

Assign a Content Template with CRED depending on Taxonomy

This CRED submit_complete hook allows you to assign a certain Content Template to a new Post (or edited) depending on the Taxonomy term assigned to the Post.

You can extend the if/elseif with more terms and taxonomies if you like
The Content Template is hardcoded, but could be extended to a $variable, it just does not make much sense

function my_success_action($post_id, $form_data) {
    // if a specific form
    if ($form_data['id']==ID){ //replace ID with actual CRED ID
            $ct_one = ID;//replace ID with the Content template ID
            $ct_two = ID;//replace ID with the Content template ID
 
            if (has_term( 'your-term', 'your-taxonomy', $post_id )){
                update_post_meta($post_id, '_views_template', $ct_one);     
            }
            elseif (has_term( 'your-second-term', 'your-taxonomy', $post_id )) {
                update_post_meta($post_id, '_views_template', $ct_two);  
            }
                 
    }
}
add_action('cred_submit_complete', 'my_success_action',10,2);

Custom logout Link

Adds a simple Logout Link with BootsTrap Style as a ShortCode to your System. Make sure to register it in Views previous to usage.

/** Custom Logout Shortcode
 */
 function custom_logout_link_func() {
            $return = wp_logout_url();?>
            <a href="<?php echo $return; ?>" class="btn btn-primary btn-xs btn-block" role="button">Logout</a>
            <?php
        }
        
    add_shortcode('logout_link', 'custom_logout_link_func');

Count Post amount per user

/**
 *Count posts of given type, so each user can create post only once
 */
function u_post_count() {
    $user_post_count = count( get_posts( array( 
    'post_type' => 'your_post_type', 
    'author'    => get_current_user_id(), 
) ) );
        
    return $user_post_count;
}

It will count all Posts of the current logged in user.
Make sure to define the Post type in 'post_type'
It returns a numeric count.