We are using Gravity Forms and need to prevent the user from accessing the form again after submission. This is the code we're using in the 'application.php' template:
<?php
if (get_current_user_id()) {
//lookup current application:
$query = "SELECT * FROM dg_application where user_id = " . get_current_user_id();
$dg_application = $wpdb->get_row( $query, ARRAY_A );
if ($dg_application["user_id"] && $dg_application["status"] == "Completed") {
// custom field
echo get_post_meta($post->ID, "form_complete_message", true);
} else {
//let Gravity Forms/WP do thier jobs
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'template-parts/content', 'page' );
// End of the loop.
endwhile;
}
} else {
echo "Sorry. You must be logged in to view this form.";
}
?>
</main><!-- .site-main -->
<?php get_sidebar( 'content-bottom' ); ?>
But it's not working and not displaying the message like it should. The database name is correct. We are using a custom database. Any ideas why it might not be showing?
I have tried many ways. not sure this is the better way or not but it's working well for me.
This code will prevent form access for the current user if they already filled the form.
add_filter( 'gform_get_form_filter_3', 'custom_schedule', 10, 2 );
function custom_schedule( $form_string, $form ) {
$current_user = wp_get_current_user();
$search_criteria = array(
'status' => 'active',
'field_filters' => array( //which fields to search
array(
'key' => 'created_by', 'value' => $current_user->ID, //Current logged in user
)
)
);
$form_id = 3;
$entry = GFAPI::get_entries($form_id,$search_criteria);
if ( !empty($entry) ) {
$form_string = '<p>Sorry, you have reached the submission limit for this form.</p>';
}
return $form_string;
}
Related
I have 2 different working methods at functions.php for backend. Each method below has 2 hooks; 1 to display the new custom field & another hook to save\update the values:
Method 1:
function media_hacks_attachment_field_to_edit( $form_fields, $post ){
// https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
$media_author = get_post_meta( $post->ID, 'media_author', true );
$form_fields['media_author'] = array(
'value' => $media_author ? $media_author : '',
'label' => __( 'Author' )
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'media_hacks_attachment_field_to_edit', null, 2 );
//Saving value on Update (method 1)
function media_hacks_edit_attachment( $attachment_id ){
if ( isset( $_REQUEST['attachments'][$attachment_id]['media_author'] ) ) {
$media_author = $_REQUEST['attachments'][$attachment_id]['media_author'];
update_post_meta( $attachment_id, 'media_author', $media_author );
}
}
add_action( 'edit_attachment', 'media_hacks_edit_attachment' );
Method 2:
function my_image_attachment_fields_to_edit($form_fields, $post) {
// $form_fields is a special array of fields to include in the attachment form
// $post is the attachment record in the database
// $post->post_type == 'attachment'
// (attachments are treated as posts in Wordpress)
// add our custom field to the $form_fields array
// input type="text" name/id="attachments[$attachment->ID][custom1]"
$form_fields["custom1"] = array(
"label" => __("Custom Text Field"),
"input" => "text", // this is default if "input" is omitted
"value" => get_post_meta($post->ID, "_custom1", true)
);
// if you will be adding error messages for your field,
// then in order to not overwrite them, as they are pre-attached
// to this array, you would need to set the field up like this:
$form_fields["custom1"]["label"] = __("Custom Text Field");
$form_fields["custom1"]["input"] = "text";
$form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);
return $form_fields;
}
// attach our function to the correct hook
add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2);
//Saving value on Update (method 2)
function my_image_attachment_fields_to_save($post, $attachment) {
// $attachment part of the form $_POST ($_POST[attachments][postID])
// $post attachments wp post array - will be saved after returned
// $post['post_type'] == 'attachment'
if( isset($attachment['custom1']) ){
// update_post_meta(postID, meta_key, meta_value);
update_post_meta($post['ID'], '_custom1', $attachment['custom1']);
}
return $post;
}
add_filter("attachment_fields_to_save", "my_image_attachment_fields_to_save", null, 2);
Here's the good result at backend Media Library (Custom Text Field & Author):
This was it for the Backend dashboard.
My question is for the Frontend:
Now how can I retrieve & display values of these 2 custom fields at the FRONTEND?
Here's my failed try at a template php page:
<tr id='MySpecialRow'>
<td colspan='2' style='background:#000;color:#fff;'>
<?php
$args = array('cat' => 8);
$query = new WP_Query($args);
if ($query->have_posts()) {
// some code here if you want.
while ($query->have_posts()) {
$query->the_post();
$untitled_meta = rwmb_meta('image_advanced_8hswqfsoqai', '', get_the_ID());
foreach ($untitled_meta as $image) {
$media_author = get_post_meta( get_the_ID(), 'media_author', true );
echo get_the_ID();//correctly prints post id
echo $media_author;//prints nothing :(
}
}
}
?>
</td>
</tr>
Small notes:
get_the_ID() does print the post id, but $media_author has no value :(
I'm doing a WordPress posts query loop because the gallery containing the custom fields exists in a Post. In other words I don't have the post Id since I'm at a Page template.
The array you got has the image post object ID as the array keys, so you need to use the extended foreach syntax to get access to the key as well.
foreach ($untitled_meta as $id => $image) {
$media_author = get_post_meta( $id, 'media_author', true );
Normally when looping over array data you rather seldom need access to the key as well, but when you do, PHP offers the $key => $value syntax to get access to the key as well, https://www.php.net/manual/en/control-structures.foreach.php
I have searched all over here and the web but cant seem to get this to work - hopefully you all can help.
I am trying to setup product filters for WooCommerce on the category page (like filter products depending on color etc)
I have the ajax working but I have a shortcode that I want to display for each product and this doesnt work - any ideas how to get it to show?
Code below:
PHP
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', plugins_url() . '/plugin-name/js/product-filter-ajax.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
JS
jQuery(document).ready(function($) {
$(".loading").hide();
var taxonomy = [];
var terms = [];
$('.filter-option input').click( function(event) {
var taxonomy_idx = $.inArray($(this).closest(".filter-title-wrapper").attr('data-attribute'), taxonomy);
if (taxonomy_idx == -1) {
taxonomy.push($(this).closest(".filter-title-wrapper").attr('data-attribute'));
} else {
taxonomy.splice(taxonomy_idx, 1);
}
var terms_idx = $.inArray($(this).val(), terms);
if (terms_idx == -1) {
terms.push($(this).val());
} else {
terms.splice(terms_idx, 1);
}
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = taxonomy.toString();;
var selected_term = terms.toString();
var selected_term_speach = '\'' + selected_term.split(',').join('\',\'') + '\'';
console.log(selecetd_taxonomy);
console.log(selected_term_speach);
// After user click on tag, fade out list of posts
$('.products').fadeOut();
$(".loading").fadeIn();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
term: selected_term_speach,
};
$.post( afp_vars.afp_ajax_url, data, function(response) {
$(".loading").fadeOut();
if( response ) {
// Display posts on page
$('.products').html( response );
// Restore div visibility
$('.products').fadeIn();
};
});
});
});
PHP TO GET POSTS
// Script for getting posts
function ajax_filter_get_posts( $taxonomy, $term ) {
ob_start();
global $woocommerce, $product;
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
$term = $_POST['term'];
$term = str_replace("\\", '', $term);
// WP Query
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
);
if ($term == "''") {
}
else {
$args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => array($term),
'field' => 'slug',
'operator' => 'IN'
),
)
);
}
?>
<h1> <?php echo $term ?> </h1>
<?php
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<li <?php wc_product_class(); ?>>
<?php echo do_shortcode('[product_shortcode]'); ?>
</li>
<?php
?>
<?php endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
return ob_get_clean();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
Excuse the messyness of the code, just trying to get it to work before I can start to neaten it up. Any advice on how to approach this in a better way please let me know.
Thanks and appreciate the help!
UPDATE-----
Tried to add the shortcode callback, but this doesnt work or I have the wrong code
add_action( 'init', function() {
ps_register_shortcode_ajax( 'ajax_filter_get_posts', 'ajax_filter_get_posts' );
} );
function ps_register_shortcode_ajax( $callable, $action ) {
if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
return;
call_user_func( $callable );
}
WordPress Ajax calls don't have the access to whole WordPress environment and that's why your shortcode not working. Instead of calling the shortcode directly, call its callback. Refer https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request for more details.
I have a custom post type named "Designer" Each posts will be using different unique Advanced Custom Fields as each posts has unique templates.With the below code I am able to give rules for each posts in Designer post type and save but the custom fields are not displaying on post edit pages on backend.
Normally this code should ork but no idea what happend to the code
Please Help.
add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices )
{
$choices['Custom Post types']['cpt_parent'] = 'Custom post type parent';
return $choices;
}
add_filter('acf/location/rule_values/cpt_parent', 'acf_location_rules_values_cpt_parent');
function acf_location_rules_values_cpt_parent( $choices )
{
$args = array(
'hierarchical' => true,
'_builtin' => false
);
$posttypes = get_post_types( $args );
if( $posttypes )
{
foreach( $posttypes as $posttype ):
if( $posttype != 'acf' ):
$args = array(
'post_type' => 'designer',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$customposts = get_posts( $args );
if ( $customposts ) {
foreach( $customposts as $custompost ){
$choices[ $custompost->ID] = $custompost->post_title;
}
}
endif;
endforeach;
}
return $choices;
}
//MATCH THE RULE
add_filter('acf/location/rule_match/cpt_parent', 'acf_location_rules_match_cpt_parent', 10, 3);
function acf_location_rules_match_cpt_parent( $match, $rule, $options )
{
global $post;
$selected_post = (int) $rule['value'];
// post parent
$post_parent = $post->post_parent;
if( $options['page_parent'] ) {
$post_parent = $options['page_parent'];
}
if ($rule['operator'] == "=="){
$match = ( $post_parent == $selected_post );
}
elseif ($rule['operator'] != "!="){
$match = ( $post_parent != $selected_post );
}
return $match;
}
Your Artist Collection field group is set to only appear on one post, the post Designer Post 1 which is a Designer Post type.
I don't understand what all the code is for? Just create a different field group for each post that needs a different field group and a separate rule for each.
Ok sorry I understand the issue now and I have recreated the issue on my local install.
On the line of code below you are looking for the post_parent but I think you should be looking for the ID.
I changed this:
$post_parent = $post->post_parent;
to this:
$post_parent = $post->ID;
and it's working for me.
If I understand your problem correctly, in wp-admin post edit page click on screen options on the upper right corner. In the menu that appears make sure the Custom fields is selected. This will make the custom fields appear for edit.
I am having a problem with multiple if statements. I am using && but it seems to only work for the first statement.
The code is like such:
global $post;
$args = array( 'post_id' => $post->ID );
$comment = get_comments( $args );
$user = wp_get_current_user();
if ( 3 <= count( $comment ) && $post->post_author == $user->ID) {
echo do_shortcode( '[button]' );
} else {
comment_form();
}
It basically stats that if there is less than 3 comments then show the comment form but if there is more than 3 and is the post author then show a button. The button shows but only if there are more than 3 comments. It doesn't check if it is only the post author or not, like I want it to.
What you are describing are two cases in which the button should be showed. So there have to be two ways to get into the if-block. You have to refactor your if-statement with the logical or-operator ||.
for example:
if($post->post_author == $user->ID || 3 <= count($comment)) {
echo do_shortcode( '[button]' );
} else {
comment_form();
}
I had to change the code like so to get it to work.
global $post,$current_user;
$args = array( 'post_id' => $post->ID );
$comment = get_comments( $args );
get_currentuserinfo();
if ($post->post_author == $current_user->ID ) {
echo do_shortcode( '[button]' );
} elseif ( 3 <= count( $comment ) ) {
// blank
} else {
comment_form();
}
I have a series of custom tables which hold distillery operations data on the same MySQL DB as my Wordpress. I would like to use WPDB->GetResults and then WP_INSERT_POST to take form data and create a custom post type from certain distillery table entries. I have an HTML form trying to send a request to a PHP file (code below). I notice that I cannot even see the PHP when opening the webpage. There must be something wrong with this. When debugging the form submission, I am good up until my $.ajax({ call, but I think the .php file is getting me down.
-Newbie doing his best
<!DOCTYPE html>
<html>
<body>
<p>Goofball</p>
<?php
require('header.php');
require('mydomain/test/wp-includes/wp-db.php')
if(isset($_POST['mashId'])){
$mashId = $_REQUEST['mashId'];
new_mash_post($mashId);
}
function new_mash_post($mashId) {
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
$mashes = $wpdb->get_results(
"
SELECT *
FROM mash a
INNER JOIN mashbill b ON a.mashId = b.mashId
INNER JOIN mash_ferm_junc c ON a.mashId = c.mashId
WHERE a.mashId = $mashId
"
);
$oldmashid = 0;
foreach($mashes as $mash){
if($oldmashid != 0){
$oldmashid = $mash->mashId;
$slug = $mash->mashId;
$title = $mash->mashId;
$author_id = 1;
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title ) ) {
// Set the post ID so that we know the post was created successfully
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'your_bottle'
)
);
$json_result = array( 'success' => true, 'post_id' => $post_id);
echo json_encode( $json_result );
// Otherwise, we'll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
echo json_encode("failed");
} // end if
} //end if mashId is new
} //end for loop over selection results
} // end programmatically_create_post
?>
</body>
</html>