Can someone point me out to how can I retrieve the up to date version number of a plugin via its web page from the WordPress plugin directory?
For example, in http://wordpress.org/extend/plugins/advanced-custom-fields/
I want to grab the 4.0.1
You can interact with the WordPress Repository API:
The WordPress Repository API is the API used to fetch plug-in and theme information.
http://wp.tutsplus.com/tutorials/creative-coding/interacting-with-wordpress-plug-in-theme-api/
I use the following in a plugin of mine. Check the comments for details.
/**
* Function used to print the data
*/
function b5f_print_repository_info( $echo = true )
{
// Grab data and do nothing if fail
$plugin_data = b5f_get_repository_info();
if( false === $plugin_data )
return;
// Custom function used to format the rating
$total_downloads = number_format_i18n( $plugin_data['total_downloads'] );
$rating = b5f_format_rating( $plugin_data['rating'] / 20 );
$updated = date_i18n( get_option( 'date_format' ), strtotime( $plugin_data['updated'] ) );
$num_rating = number_format_i18n( $plugin_data['num_ratings'] );
$version = $plugin_data['version'];
if( $echo )
echo 'Your stuff using the variables above.';
else
return 'Your stuff using the variables above.';
}
/**
* Call WP API and return the data
*/
function b5f_get_repository_info()
{
$plugin_url = 'http://wpapi.org/api/plugin/advanced-custom-fields.json';
// Cache
$cache = get_transient( 'my_plugin_transient' );
if( false !== $cache )
return $cache;
// Fetch the data
if( $response = wp_remote_retrieve_body( wp_remote_get( $plugin_url ) ) )
{
// Decode the json response
if( $response = json_decode( $response, true ) )
{
// Double check we have all our data
if( !empty( $response['added'] ) )
{
set_transient( 'my_plugin_transient', $response, 720 );
return $response;
}
}
}
return false;
}
/**
* Auxiliary function to format the Rating
*/
function b5f_format_rating( $number, $cents = 1 )
{
// Check if value can be dealt with
if( !is_numeric( $number ) )
return $number;
if( !$number ) {
$rating = ($cents == 2) ? '0.00' : '0';
}
else {
if( floor( $number ) == $number ) {
$rating = number_format( $number, ($cents == 2 ? 2 : 0 ) );
}
else {
$rating = number_format( round( $number, 2 ), ($cents == 0 ? 0 : 2 ) );
}
}
return $rating;
}
And the following is a shortened version of the response, description and stats fields are really big.
Array
(
[added] => 2011-03-25
[author] => Array
(
[name] => Elliot Condon
[url] => http://www.elliotcondon.com/
[profile] => http://profiles.wordpress.org/elliotcondon
)
[average_downloads] => 1415.61
[contributors] => Array
(
[contributor-Elliot Condon] =>
)
[download_link] => http://downloads.wordpress.org/plugin/advanced-custom-fields.zip
[hits] => 0
[homepage] => http://www.advancedcustomfields.com/
[last_update_details] => 2013-04-30 17:36:06
[last_update_stats] => 2013-04-30 17:36:05
[name] => Advanced Custom Fields
[num_ratings] => 905
[rating] => 98
[requires] => 3.0.0
[sections] => Array
(
[description] => <p>Advanced Custom Fields is
)
[slug] => advanced-custom-fields
[stats] => Array
(
[2011-11-09] => 683
)
[tags] => Array
(
[tag-admin] => admin
[tag-advanced] => advanced
[tag-custom] => custom
[tag-custom-field] => custom field
[tag-edit] => edit
[tag-field] => field
[tag-file] => file
[tag-image] => image
[tag-magic-fields] => magic fields
[tag-matrix] => matrix
[tag-more-fields] => more fields
[tag-post] => Post
[tag-repeater] => repeater
[tag-simple-fields] => simple fields
[tag-text] => text
[tag-textarea] => textarea
[tag-type] => type
)
[tested] => 3.5.1
[total_days] => 539
[total_downloads] => 763012
[type] => plugin
[updated] => 2013-04-30
[version] => 4.1.0
)
Related
I'm using custom fields in the comment form "Did you like this book?" and "yes" and "no" values. I want to send 2 different auto-replies to a comment, if the user selects "yes" then the response is "Thank you for your kind recognition, customer's satisfaction is always our goal." and if "no" then the auto answer is "We'll strive to do better." I would appreciate any of your help...
//And this is how I send an auto reply to a comment
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $commentdata ){
$comment_parent = (int) $commentdata['comment_parent'];
// If a new comment is a reply to another comment, don't do anything
if ( $comment_parent !== 0 ) {
return;
}
//How do I add a response if the comment contains the value of the [likebook ] meta field???
if( !empty( $_POST['likebook'] ) {
return;
}
$commentdata = [
'comment_post_ID' => $commentdata['comment_post_ID'],
'comment_author' => 'admin',
'comment_author_email' => 'admin#example.com',
'comment_author_url' => 'http://example.com',
'comment_content' => 'Thank you for your kind recognition, customer satisfaction is always our goal.',
'comment_type' => 'comment',
'comment_parent' => $comment_ID,
'user_ID' => 1,
];
wp_new_comment( $commentdata );
}
try these,
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $comment ) {
if ( $comment['comment_parent'] !== 0 ) {
return;
}
if ( ! empty( $_POST['like'] ) ) {
if ( $_POST['like'] == 'dog' ) {
$msg = 'We are glad that you liked it!';
} else {
$msg = 'We will try to make this product better!';
}
$admins = get_super_admins();
$current_user = get_user_by( 'login', $admins[0] );
$data = array(
'comment_post_ID' => $comment['comment_post_ID'],
'comment_content' => $msg,
'comment_parent' => $comment_ID,
'user_id' => $current_user->ID,
'comment_author' => $current_user->user_login,
'comment_author_email' => $current_user->user_email,
'comment_author_url' => $current_user->user_url
);
$comment_id = wp_insert_comment( $data );
if ( is_wp_error( $comment_id ) ) {
throw new Exception( $comment_id );
}
}
}
Let's say you create a WordPress post and assign it a meta key foo with value bar. You only want to display an ACF field if foo is equal to bar. However, there's no built-in location rule in ACF to do this. How would you solve this problem by creating an ACF custom location rule?
In order to display ACF fields if a post meta key is equal or not equal to some value, use the following snippet. It's based off of the ACF Custom Location Rules guide.
if( ! defined( 'ABSPATH' ) ) exit;
class My_ACF_Location_Post_Meta extends ACF_Location {
public function initialize() {
$this->name = 'post_meta';
$this->label = __( "Post Meta", 'acf' );
$this->category = 'post';
$this->object_type = 'post';
}
public function rule_values($choices, $rule){
if(!acf_is_screen('acf-field-group') && !acf_is_ajax('acf/field_group/render_location_rule')){
return array(
$rule['meta_key'] => $rule['meta_key'],
$rule['meta_value'] => $rule['meta_value']
);
}
ob_start();
acf_render_field(array(
'type' => 'text',
'name' => 'meta_key',
'prefix' => 'acf_field_group[location]['.$rule['group'].']['.$rule['id'].']',
'value' => (isset($rule['meta_key']) ? $rule['meta_key'] : ''),
'placeholder' => 'Meta Key'
));
acf_render_field(array(
'type' => 'text',
'name' => 'meta_value',
'prefix' => 'acf_field_group[location]['.$rule['group'].']['.$rule['id'].']',
'value' => (isset($rule['meta_value']) ? $rule['meta_value'] : ''),
'placeholder' => 'Meta Value'
));
return ob_get_clean();
}
public function rule_operators($choices, $rule){
$choices = [];
$choices['key_is_equal_to_value'] = __('key is equal to value', 'acf');
$choices['key_is_not_equal_to_value'] = __('key is not equal to value', 'acf');
return $choices;
}
public function match( $rule, $screen, $field_group ) {
// Check screen args for "post_id" which will exist when editing a post.
// Return false for all other edit screens.
if( isset($screen['post_id']) ) {
$post_id = $screen['post_id'];
} elseif (isset($screen['attachment_id'])) {
$post_id = $screen['attachment_id'];
} else {
return false;
}
// Load the post meta object for this edit screen.
$post_meta_value = get_post_meta( $post_id, $rule['meta_key'], true );
if( !$post_meta_value ) {
return false;
}
// Compare the Post's meta value to rule meta value.
$result = ( strval($post_meta_value) == $rule['meta_value'] );
// Return result taking into account the operator type.
if( $rule['operator'] == 'key_is_not_equal_to_value' ) {
return !$result;
}
return $result;
}
}
add_action('acf/init', 'my_acf_init_location_types');
function my_acf_init_location_types() {
// Check function exists, then include and register the custom location type class.
if( function_exists('acf_register_location_type') ) {
acf_register_location_type( 'My_ACF_Location_Post_Meta' );
}
}
I need to validate an email field in gravity form. We have some known list of email domains and need to validate whether that domains present or not and If that domains present means we need to show the error message.
What is the best way to implement that? Any plugin suggestions?
This is possible with the GW_Email_Domain_Validator snippet here:
https://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
Full snippet as of July 18, 2020 included here. Use the link above to get the latest version.
<?php
/**
* Gravity Wiz // Gravity Forms // Email Domain Validator
*
* This snippets allows you to exclude a list of invalid domains or include a list of valid domains for your Gravity Form Email fields.
*
* #version 1.4
* #author David Smith <david#gravitywiz.com>
* #license GPL-2.0+
* #link http://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
*/
class GW_Email_Domain_Validator {
private $_args;
function __construct($args) {
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'field_id' => false,
'domains' => false,
'validation_message' => __( 'Sorry, <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'ban' // also accepts "limit"
) );
// convert field ID to an array for consistency, it can be passed as an array or a single ID
if($this->_args['field_id'] && !is_array($this->_args['field_id']))
$this->_args['field_id'] = array($this->_args['field_id']);
$form_filter = $this->_args['form_id'] ? "_{$this->_args['form_id']}" : '';
add_filter("gform_validation{$form_filter}", array($this, 'validate'));
}
function validate($validation_result) {
$form = $validation_result['form'];
foreach($form['fields'] as &$field) {
// if this is not an email field, skip
if(RGFormsModel::get_input_type($field) != 'email')
continue;
// if field ID was passed and current field is not in that array, skip
if($this->_args['field_id'] && !in_array($field['id'], $this->_args['field_id']))
continue;
$page_number = GFFormDisplay::get_source_page( $form['id'] );
if( $page_number > 0 && $field->pageNumber != $page_number ) {
continue;
}
if( GFFormsModel::is_field_hidden( $form, $field, array() ) ) {
continue;
}
$domain = $this->get_email_domain($field);
// if domain is valid OR if the email field is empty, skip
if($this->is_domain_valid($domain) || empty($domain))
continue;
$validation_result['is_valid'] = false;
$field['failed_validation'] = true;
$field['validation_message'] = sprintf($this->_args['validation_message'], $domain);
}
$validation_result['form'] = $form;
return $validation_result;
}
function get_email_domain( $field ) {
$email = explode( '#', rgpost( "input_{$field['id']}" ) );
return trim( rgar( $email, 1 ) );
}
function is_domain_valid( $domain ) {
$mode = $this->_args['mode'];
$domain = strtolower( $domain );
foreach( $this->_args['domains'] as $_domain ) {
$_domain = strtolower( $_domain );
$full_match = $domain == $_domain;
$suffix_match = strpos( $_domain, '.' ) === 0 && $this->str_ends_with( $domain, $_domain );
$has_match = $full_match || $suffix_match;
if( $mode == 'ban' && $has_match ) {
return false;
} else if( $mode == 'limit' && $has_match ) {
return true;
}
}
return $mode == 'limit' ? false : true;
}
function str_ends_with( $string, $text ) {
$length = strlen( $string );
$text_length = strlen( $text );
if( $text_length > $length ) {
return false;
}
return substr_compare( $string, $text, $length - $text_length, $text_length ) === 0;
}
}
To only accept submissions from a given email domain you can do something like this:
new GW_Email_Domain_Validator( array(
'form_id' => 326,
'field_id' => 1,
'domains' => array( 'gmail.com', 'hotmail.com', '.co.uk' ),
'validation_message' => __( 'Oh no! <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'limit'
) );
I have products from some API and want to insert these products. I was able to insert products and use already existing attributes ( or added by UI ).
Adding new term (My Color) to the existing attribute (Color) :
// Add term to the attribute
wp_set_object_terms( $post_id, "My Color", 'pa_color' , true );
Use the added attribute with current product :
// Data for the term to be used
$theData = array(
'pa_color'=>
array(
'name'=>'pa_color',
'value'='My Color',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
)
);
// Add this attribute to this product
update_post_meta( $post_id,'_product_attributes',$theData);
How can I add new attribute and use it with the current product, for ex :
RAM : 4GB
I have tried this :
register_taxonomy(
'pa_ram',
'product',
array(
'label' => __( 'RAM' ),
'rewrite' => array( 'slug' => 'size' ),
'hierarchical' => true,
)
);
}
Here is the URL of the attributes I can see/add in UI :
wp-admin/edit.php?post_type=product&page=product_attributes
This did the job for me :
// Insert new attribute
function process_add_attribute($attribute) {
global $wpdb;
if (empty($attribute['attribute_type'])) {
$attribute['attribute_type'] = 'select';
}
if (empty($attribute['attribute_orderby'])) {
$attribute['attribute_orderby'] = 'name';
}
if (empty($attribute['attribute_public'])) {
$attribute['attribute_public'] = 1;
}
if (empty($attribute['attribute_name']) || empty($attribute['attribute_label'])) {
return new WP_Error('error', __('Please, provide an attribute name and slug.', 'woocommerce'));
}
elseif(($valid_attribute_name = valid_attribute_name($attribute['attribute_name'])) && is_wp_error($valid_attribute_name)) {
return $valid_attribute_name;
}
$wpdb->insert($wpdb->prefix.'woocommerce_attribute_taxonomies', $attribute);
do_action('woocommerce_attribute_added', $wpdb->insert_id, $attribute);
flush_rewrite_rules();
delete_transient('wc_attribute_taxonomies');
return true;
}
function valid_attribute_name( $attribute_name ) {
if ( strlen( $attribute_name ) >= 28 ) {
return new WP_Error( 'error', sprintf( __( 'Slug "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
} elseif ( wc_check_if_attribute_name_is_reserved( $attribute_name ) ) {
return new WP_Error( 'error', sprintf( __( 'Slug "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
}
return true;
}
Call it like :
// Add new attribute
$status = process_add_attribute(array(
'attribute_name' => 'myattribute',
'attribute_label' => 'My Attribute'
));
// Added successfully
if (!is_wp_error($status)) {
// Continue
}
I am trying to modify a plugin. I need the author id of the current post to accomplish what I am doing. I have tried every other method I have found over internet that claims to get the post author id outside the loop but its not working inside the plugin. I guess its because the plugins might be loaded before the loop variables or something? Please pardon me as I am not a Pro.
Here is what I have tried so far.
1.
$author_id=$post->post_author;
2.
global $post;
$author_id=$post->post_author;
3.
$post_tmp = get_post($post_id);
$author_id = $post_tmp->post_author;
4.
$author_id = $posts[0]->post_author;
But nothing works in the plugin's directory. Can anyone help?
Detailed Explanation:
I am trying to modify woodiscuz plugin. The problem with this plugin is that it held comments of even seller for moderation. So if I am the seller and I reply to some buyer in comment, I will have to approve my own comment.
Now to overcome this problem, I am putting a condition that if the author of the post (seller) is commenting, then don't put the comment for moderation.
Here is the function of the plugin that is controlling comments.
public function comment_submit_via_ajax() {
$message_array = array();
$comment_post_ID = intval(filter_input(INPUT_POST, 'comment_post_ID'));
$comment_parent = intval(filter_input(INPUT_POST, 'comment_parent'));
if (!$this->wpc_options->wpc_options_serialized->wpc_captcha_show_hide) {
if (!is_user_logged_in()) {
$sess_captcha = $_SESSION['wpc_captcha'][$comment_post_ID . '-' . $comment_parent];
$captcha = filter_input(INPUT_POST, 'captcha');
if (md5(strtolower($captcha)) !== $sess_captcha) {
$message_array['code'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_captcha'];
echo json_encode($message_array);
exit;
}
}
}
$comment = filter_input(INPUT_POST, 'comment');
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$user = get_userdata($user_id);
$name = $user->display_name;
$email = $user->user_email;
$user_url = $user->user_url;
} else {
$name = filter_input(INPUT_POST, 'name');
$email = filter_input(INPUT_POST, 'email');
$user_id = 0;
$user_url = '';
}
$comment = wp_kses($comment, array(
'br' => array(),
'a' => array('href' => array(), 'title' => array()),
'i' => array(),
'b' => array(),
'u' => array(),
'strong' => array(),
'p' => array(),
'img' => array('src' => array(), 'width' => array(), 'height' => array(), 'alt' => array())
));
$comment = $this->wpc_helper->make_clickable($comment);
if ($name && filter_var($email, FILTER_VALIDATE_EMAIL) && $comment && filter_var($comment_post_ID)) {
$held_moderate = 1;
if ($this->wpc_options->wpc_options_serialized->wpc_held_comment_to_moderate) {
$held_moderate = 0;
}
// $held_moderate = 1 -> No moderation
/*This is the part where I need to put the custom condition*/
if($post_author_id == get_current_user_id())
{
$held_moderate = 1;
}
$new_commentdata = array(
'user_id' => $user_id,
'comment_post_ID' => $comment_post_ID,
'comment_parent' => $comment_parent,
'comment_author' => $name,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_author_url' => $user_url,
'comment_type' => 'woodiscuz',
'comment_approved' => $held_moderate
);
$new_comment_id = wp_insert_comment($new_commentdata);
$new_comment = new WPC_Comment(get_comment($new_comment_id, OBJECT));
if (!$held_moderate) {
$message_array['code'] = -2;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_held_for_moderate'];
} else {
$message_array['code'] = 1;
$message_array['message'] = $this->comment_tpl_builder->get_comment_template($new_comment);
}
$message_array['wpc_new_comment_id'] = $new_comment_id;
} else {
$message_array['code'] = -1;
$message_array['wpc_new_comment_id'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_field'];
}
echo json_encode($message_array);
exit;
}