ACF Field Wordpress - Custom Shortcode Problems - wordpress

I have a small problem
I wrote a simple shortcode function to display my acf value in the grid of the visual grid composer, this is my simple custom shortcode
function my_module_add_grid_shortcodes( $shortcodes ) {
$shortcodes['vc_say_hello'] = array(
'name' => __( 'Say Hello', 'my-text-domain' ),
'base' => 'vc_say_hello',
'category' => __( 'Content', 'my-text-domain' ),
'description' => __( 'Just outputs Hello World', 'my-text-domain' ),
'post_type' => Vc_Grid_Item_Editor::postType(),
);
return $shortcodes;
}
add_shortcode( 'vc_say_hello', 'vc_say_hello_render' );
function vc_say_hello_render() {
if( get_field('item') ):
the_field('item');
else:
echo "<h2>ITEM LOCKED</h2>";
endif;
}
When I call the shortcode in the builder, "ITEM Locked" is displayed, even if the value of the element is set in the post !!!

Looks like get_field doesn't know where to get it from in the shortcode. Try adding the current post id as the second parameter
add_shortcode( 'vc_say_hello', 'vc_say_hello_render' );
function vc_say_hello_render() {
$id = get_the_ID();
if( get_field('item', $id) ):
the_field('item', $id);
else:
echo "<h2>ITEM LOCKED</h2>";
endif;
}

Related

Bulk update all taxonomy terms in wordpress

My custom post type "references" has a custom field called "references_count". It has a numeric value.
I have an custom taxonomy called "country" with a custom field called "country_count" for the terms.
Background:
The custom post type "references" saves cities with a number of clients in this city. This value is saved in the field "references_count". In the custom taxonomy there are countries. For each country, there is a total number of references.
Example:
In the city of "Berlin" there are 3 clients. In the city of "Munich" there are 2 clients. The taxonomy term "Germany" includes the sum of all cities in this country. So the value of "country_count" in this example for the taxonomy term "Germany" is 5, being the sum of the references of each city.
I wrote this code which is working, if I'm saving each individual taxonomy term.
add_action( 'edited_country', 'update_counter_for_countries', 10, 2 );
function update_counter_for_countries( $term_id ) {
// Get posts with term
$args = array(
'post_type' => 'reference',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'country',
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
// sum values in posts
$sumTerm = 0;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$number = get_field( 'references_count', get_the_ID() );
$sumTerm = $sumTerm + $number;
}
}
wp_reset_postdata();
// update field in term
update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );
}
Problem:
I have more than 100 countries (taxonomy terms), so I have to save each term individually to get things going.
What I am looking for: Is there a way to update / save all custom taxonomy terms at once, so I don't have to update each term seperately? I checked out a lot of plugins, but couldn't find any plugin which gives the possibility of "bulk edit" or "bulk save" taxonomy terms. I would prefer a solution without plugin if possible. I am very grateful for any hint, thank you very much.
You can use this code to update all terms in one go.
Just make sure to backup your database in case needed.
This code will loop through all the terms and will only run once. after that you can remove this code.
Just to make this code run only on your IP, change 111.111.111.111 to your IP ADDRESS.
if($_SERVER["REMOTE_ADDR"]=='111.111.111.111'){
//run only my ip
add_action("init","update_all_terms_in_one_go");
}
function update_all_terms_in_one_go(){
session_start();
if(isset($_SESSION['all_terms_updated']) && $_SESSION['all_terms_updated'] == "done"){
return;
}
$taxonomy = "country";
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
]);
foreach ($terms as $term) {
update_counter_for_countries( $term->term_id );
}
$_SESSION['all_terms_updated'] = "done";
echo "ALL TAXONOMY TERMS UPDATED";
die();
}
function update_counter_for_countries( $term_id ) {
// Get posts with term
$args = array(
'post_type' => 'reference',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'country',
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
// sum values in posts
$sumTerm = 0;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$number = get_field( 'references_count', get_the_ID() );
$sumTerm = $sumTerm + $number;
}
}
wp_reset_postdata();
// update field in term
update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );
}
I wanted to have a neat admin page with a button to bulk update all my taxonomy terms. The process should work using AJAX so it can take a while without confusing the user. There should be status messages.
So in the first step I added a new admin page to the wordpress backend.
add_action( 'admin_menu', array( $this, 'my_admin_page' ) );
function my_admin_page() {
add_menu_page(
__('Bulk Terms'), // page title
__('Bulk Terms'), // menu title
'manage_options', // user capabilities
'options-page', // menu slug
'my_output_function', // output function
'dashicons-admin-generic', // menu icon
77 // menu position
);
}
In the output function I put a form with a button to bulk update terms. And some status messages.
function my_output_function() {
echo '<div class="wrap">';
echo '<form action="admin.php?page=options-page" method="post">';
wp_nonce_field( 'ajax_validation', 'nonce' ); // security feature
submit_button('Update Terms', 'primary', 'submitOptions', false);
echo '</form>';
echo '<div id="processing" style="display:none;">Please wait</div>';
echo '<div id="error" style="display:none;">Something went wrong</div>';
echo '<div id="success" style="display:none;">Done!</div>';
echo '</div>';
}
In the second step I had to enqueue script file for ajax calls:
add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );
function my_ajax_scripts() {
// Check if on specific admin page
global $pagenow;
if (( $pagenow == 'admin.php' ) && ($_GET['page'] == 'options-page')):
wp_enqueue_script( 'ajaxcalls', plugin_dir_url( __FILE__ ).'/js/ajax-calls.js', array('jquery'), '1.0.0', true );
wp_localize_script( 'ajaxcalls', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_validation' )
) );
endif;
}
And create the function to bulk update all my taxnomy terms:
function options_page_action() {
$taxonomy = "country";
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
]);
foreach ($terms as $term) {
$term_id = $term->term_id;
// Get posts with term
$args = array(
'post_type' => 'reference',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'country',
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
// sum values in posts
$sumTerm = 0;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$number = get_field( 'references_count', get_the_ID() );
$sumTerm = $sumTerm + $number;
}
}
wp_reset_postdata();
// update field in term
update_field( 'country_count', $sumTerm, 'country'.'_'.$term_id );
}
$result = array( 'status' => 'success' ); // create response
wp_send_json_success( $result ); // send response
wp_die(); // close ajax request
}
As the third step, in my ajax_calls.js file I take the click event to call the function for updating the taxonomy terms using ajax.
$( '#submitOptions' ).click( function(event) {
event.preventDefault();
$('#submitOptions').css('cssText','display:none;');
$('#processing').css('cssText','display: block;');
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'options_page_action',
nonce: ajax_object.ajaxnonce
},
success: function( response ) {
if( response['data']['status'] == 'success' ) {
$('#processing').css('cssText','display:none;');
$('#success').css('cssText','display:block;');
}
},
error: function() {
$('#processing').css('cssText','display:none;');
$('#error').css('cssText','display:block;');
}
});
});
There are messages indicating that the function is running and it show messages when it's done or has an error. This way the user will always know what's going on when bulk updating terms.

Removing specific widgets from specific pages

I have specific pages that I need specific widgets to be hidden from the sidebar. I have
-5 pages that are supposed to only display nav_menu-1
-6 other pages that are supposed to display only nav_menu-2
-and then all single-posts that are supposed to only show nav_menu-3
I have this code
add_filter( 'widget_display_callback', 'widget_display_2', 50, 3 );
function widget_display_2( $instance, $widget, $args ){
if ( is_single() && $widget->id == 'nav_menu-1' ) {
return false;
}
return $instance;
}
but what is the best way to insert all my pages and widget IDs to achieve my goal?
It may sound weird but why not using three different sidebars and call them by condition. This way your Theme would become more flexible. It´s always bad to hardcode this into your theme or plugin.
// Register Sidebars
function custom_sidebars() {
$args = array(
'id' => 'custom-sidebar-1',
'name' => __( 'Custom Sidebar 1', 'text_domain' ),
);
register_sidebar( $args );
$args = array(
'id' => 'custom-sidebar-2',
'name' => __( 'Custom Sidebar 2', 'text_domain' ),
);
register_sidebar( $args );
$args = array(
'id' => 'custom-sidebar-3',
'name' => __( 'Custom Sidebar 3', 'text_domain' ),
);
register_sidebar( $args );
}
add_action( 'widgets_init', 'custom_sidebars' );
... after you added this to your functions.php you can call the different sidebars with conditional functions.
<?php
/** call custom sidebar on single.php template **/
if ( is_single() ){
dynamic_sidebar( 'custom-sidebar-1' );
}
?>
<?php
/** call custom sidebar on page.php template (all pages) **/
if ( is_page() ){
dynamic_sidebar( 'custom-sidebar-2' );
}
?>
<?php
/** call custom sidebar on multiple pages by id **/
if ( is_page( array( 11, 22, 33, 44 ) ) ){
dynamic_sidebar( 'custom-sidebar-3' );
}
?>

Shortcode issue

I am currently creating a shortcode in order to display custom taxonomy terms as a list in my template :
// First we create a function
function list_terms_forme_juridique_taxonomy( $atts ) {
// Inside the function we extract custom taxonomy parameter of our
shortcode
extract( shortcode_atts( array(
'custom_taxonomy' => 'forme_juridique',
),
$atts ) );
// arguments for function wp_list_categories
$args = array(
taxonomy => $custom_taxonomy,
title_li => ''
);
// We wrap it in unordered list
echo '<ul>';
echo wp_list_categories($args);
echo '</ul>';
}
// Add a shortcode that executes our function
add_shortcode( 'forme_juridique', 'list_terms_forme_juridique_taxonomy'
);
I run in the 2 following issues :
The shortcode (render) is displayed at the top of my page, not where I've placed it in the page;
PHP Console flag the 2 followings errores :
Use of undefined constant taxonomy - assumed 'taxonomy'
Use of undefined constant title_li - assumed 'title_li'
Any help appreciated!
Thanks
Firstly the output of your shortcode is displaying at the top of your page because you're echoing the output. You should create a $output variable and build it up with what you want to display, and then return it. For example:
$output = '';
$output .= '<ul>';
$output .= wp_list_categories($args);
$output .= '</ul>';
return $output;
Secondly you're getting the errors because you've not quoted the keys in your array declaration. Therefore PHP assumes they should be constants that were previously defined.
$args = array(
taxonomy => $custom_taxonomy,
title_li => ''
);
Should be:
$args = array(
'taxonomy' => $custom_taxonomy,
'title_li' => ''
);

WP Bakery custom template variable not working

I'm trying to add in grid builder a custom shortcode. The shortcode is working as expected but the printed value is empty.
add_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' );
function my_module_add_grid_shortcodes( $shortcodes ) {
$shortcodes['vc_custom_post_press_link'] = array(
'name' => __( 'Press link', 'domain' ),
'base' => 'vc_custom_post_press_link',
'category' => __( 'Content', 'my-text-domain' ),
'description' => __( 'Show custom post meta', 'my-text-domain' ),
'post_type' => Vc_Grid_Item_Editor::postType(),
);
return $shortcodes;
}
// output function
add_shortcode( 'vc_custom_post_press_link', 'vc_custom_post_press_link_render' );
function vc_custom_post_press_link_render($atts, $content, $tag) {
return 'test1 {{ press_link }}';
}
add_filter( 'vc_gitem_template_attribute_press_link', 'vc_gitem_template_attribute_press_link ', 10, 2 );
function vc_gitem_template_attribute_press_link( $value, $data ) {
return 'test2';
}
The expected output should be
test1 test2
but i only get
test1
The original code came from the official doc but it doesn't seem to work.
EDIT:
I just tried and the code in the documentation dont work too. I guess its not updated. I need a way to get the value of an ACF field and append some HTML around it.
Solved! The problem was in this line
add_filter( 'vc_gitem_template_attribute_press_link', 'vc_gitem_template_attribute_press_link ', 10, 2 );
that should have been
add_filter( 'vc_gitem_template_attribute_press_link', 'vc_gitem_template_attribute_press_link', 10, 2 );
Notice the missing space at the end of vc_gitem_template_attribute_press_link.

how can i display product's custom field in wp-admin/edit.php?post_type=product ( product listing table in admin ) woocommerce

I have added some custom fields in woocommerce when adding product. Now i want to display those custom fields in product listing page ( wp-admin/edit.php?post_type=product ). I also want to quick edit and save like other values can be edit and save in listing page.
I tried bellow code but it did not work.
add_filter( 'manage_edit-product', 'show_product_order' );
function show_product_order($columns){
$new_columns = (is_array($columns)) ? $columns : array();
unset( $new_columns['order_actions'] );
$new_columns['product_order'] = 'Product Order';
$new_columns['order_actions'] = $columns['order_actions'];
return $new_columns;
}
I also tried below code but it did not worked too.
add_action( 'woocommerce_product_options_general_product_data', 'woocommerce_general_product_data_custom_field' );
function woocommerce_general_product_data_custom_field() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_checkbox(
array(
'id' => 'product_order',
'wrapper_class' => 'checkbox_class',
'label' => __('Order for Product', 'woocommerce' ),
'description' => __( 'Order for Product', 'woocommerce' )
)
);
echo '</div>';
}
i also reffered this post WooCommerce show custom column but i did not succeed to get solution
Please help.

Resources