WordPress Getting post data for Post Grid of Visual Composer - php

I'm using Visual Composer in WordPress and I want to make a custom Post Grid. But the default elements that the post grid supplies are not enough. I want to show the author of the post, the number of comments it has, the category it has and the Tags it has as well. I'm not really familiar with Visual Composer, but I need a point in the right direction for me to get this data? What can I do? I've search their documents but with no luck. If I need to move around the php code I would like to know what I'm moving around is the right thing. Any ideas? If you need any more information please do ask :D
Thanks in advance for the help.

If anybody is still looking to find out how to to get the id in a post grid or create a specific widget for the grid you can use the following snippet I creatd for adding an icon before the post title. You will see inside the first function you can call $post-ID for use on any query.
//** Case Study Title Block Shortcodes ***********
//********************************
add_filter( 'vc_gitem_template_attribute_case_study_title','vc_gitem_template_attribute_case_study_title', 10, 2 );
function vc_gitem_template_attribute_case_study_title( $value, $data ) {
extract( array_merge( array(
'post' => null,
'data' => '',
), $data ) );
$atts_extended = array();
parse_str( $data, $atts_extended );
$atts = $atts_extended['atts'];
// write all your widget code in here using queries etc
$title = get_the_title($post->ID);
$link = get_permalink($post->ID);
$terms = get_the_terms($post->ID, 'case_categories');
$output = "<h4 class=\"case-title\">". get_the_icon($terms[0]->term_id) . $title ."</h4>";
return $output;
}
add_filter( 'vc_grid_item_shortcodes', 'case_study_title_shortcodes' );
function case_study_title_shortcodes( $shortcodes ) {
$shortcodes['vc_case_study_title'] = array(
'name' => __( 'Case Study Title', 'sage' ),
'base' => 'vc_case_study_title',
'icon' => get_template_directory_uri() . '/assets/images/icon.svg',
'category' => __( 'Content', 'sage' ),
'description' => __( 'Displays the case study title with correct icon', 'sage' ),
'post_type' => Vc_Grid_Item_Editor::postType()
);
return $shortcodes;
}
add_shortcode( 'vc_case_study_title', 'vc_case_study_title_render' );
function vc_case_study_title_render($atts){
$atts = vc_map_get_attributes( 'vc_case_study_title', $atts );
return '{{ case_study_title }}';
}

I got the same issue; here is how I solve it:
According to Visual Composer documentation: https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/
When you add the code below to functions.php, a new component will be added in your custom grid builder (in my example the name will be "Author"). There are a number of values you can get by post data template variable function and one of it not the name of the author but their ID (that's sad but at least you can use this value to get the author name).
The value is 'post_author' => ID of the author (for example '1')
Here is the function where I get the post author and display it (if author component was added to your custom grid in "custom grid builder"). Put it in functions.php of your child theme:
add_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' );
function my_module_add_grid_shortcodes( $shortcodes ) {
$shortcodes['vc_post_id'] = array(
'name' => __( 'Author', 'my-text-domain' ),
'base' => 'vc_post_id',
'category' => __( 'Content', 'my-text-domain' ),
'description' => __( 'Show current post author', 'my-text-domain' ),
'post_type' => Vc_Grid_Item_Editor::postType(),
);
return $shortcodes;
}
// output function
add_shortcode( 'vc_post_id', 'vc_post_id_render' );
function vc_post_id_render() {
$nn = '{{ post_data:post_author }}'; // usage of template variable post_data with argument "post_author"
return get_the_author($nn);
}
There is a little problem. It works but get_the_author is a deprecated function in WordPress. I'd appreciate any suggestions to make it more modern or if you name other alternatives please suggest.
Also, here is the list of available variables of vc_post_id_render from docs. Here they are:
WP_Post::__set_state(array(
'ID' => 69,
'post_author' => '1',
'post_date' => '2015-04-29 14:15:56',
'post_date_gmt' => '2015-04-29 14:15:56',
'post_content' => 'Your post content',
'post_title' => 'Your post title',
'post_excerpt' => '',
'post_status' => 'publish',
'comment_status' => 'open',
'ping_status' => 'open',
'post_password' => '',
'post_name' => 'post name',
'to_ping' => '',
'pinged' => '',
'post_modified' => '2015-06-17 11:18:41',
'post_modified_gmt' => '2015-06-17 11:18:41',
'post_content_filtered' => '',
'post_parent' => 0,
'guid' => 'http://wp.master/?p=69',
'menu_order' => 0,
'post_type' => 'post',
'post_mime_type' => '',
'comment_count' => '0',
'filter' => 'raw',
'filter_terms' =>
array (
),
))

this is your response
https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/
at Template variables usage
Exemple, in visual composer template you can use {{ post_date:ID }} to show post ID. I don't know how show tag.

Related

Show WooCommerce custom checkout fields using a WP_Query

I use a plugin to create some custom B2B fields. Now I need these custom made fields to be shown at the checkout page.
function add_custom_b2b_fields_checkout( $fields ){
$args = array(
'post_type' => 'afreg_fields',
'post_status' => 'publish',
'posts_per_page' => '99',
'orderby' => 'name',
);
$get_b2b_fields = new WP_Query( $args );
if ($get_b2b_fields->have_posts()) : while ($get_b2b_fields->have_posts()) : $get_b2b_fields->the_post();
$fields['billing'][$get_b2b_fields->post_name] = array(
'type' => 'text',
'label' => get_the_title(),
'placeholder' => __(" ", "woocommerce"),
'class' => array('b2b-field'),
'required' => false,
);
endwhile;
return $fields;
endif;
}
add_filter( 'woocommerce_checkout_fields', 'add_custom_b2b_fields_checkout' );
The code works nice almost. But it shows only the last field, as if the while run correctly but the return $fields shows only the first custom field instead of all of them.
How can I show all the fields instead of just one? I tried adding a .= at the $fields but that didn't work.
There is a little mistake in your code as $get_b2b_fields->post_name is empty.
Simply replace:
$fields['billing'][$get_b2b_fields->post_name] = array(
with:
$fields['billing'][$get_b2b_fields->post->post_name] = array(
Now it will work.
add_filter( 'woocommerce_checkout_fields', 'add_custom_b2b_fields_checkout' );
change it to
add_action( 'woocommerce_checkout_fields', 'add_custom_b2b_fields_checkout' );
and add do_action('woocommerce_checkout_fields'); on the page where you want to show

Wordpress wp_insert_post is creating new Taxonomy term when creating new custom post

In my WordPress v5.5.1, I am using public front-end form to create custom post type. I am saving the form data as custom post with below code:
function save_function() {
// MESSAGE FIELDS
$public_post = array(
'post_title' => filter_input(INPUT_POST, 'title'),
'post_author' => 1,
'post_type' => 'message',
'post_status' => 'pending',
'tax_input' => array(
'my_custom_taxonomy' => array(filter_input(INPUT_POST, 'subject')) // subject is a HTML select which captures option value contains term_id which is generated using get_terms.
)
);
wp_insert_post($public_post);
}
Instead of 'tax_input' tag this post to the existing custom_taxonomy term, it is creating a duplicate term with term_id as term name.
Hello Plese Try This Func
function save_function()
{
$subject_term = 'subject';
$my_subject_term = term_exists($subject_term, 'my_custom_taxonomy'); // check if term in website or no
// Create Term if it doesn't exist
if (!$my_subject_term) {
$my_subject_term = wp_insert_term($subject_term, 'my_custom_taxonomy');
}
$custom_tax = array(
'my_custom_taxonomy' => array(
$my_subject_term['term_taxonomy_id'],
)
);
// MESSAGE FIELDS
$public_post = array(
'post_title' => filter_input(INPUT_POST, 'title'),
'post_author' => 1,
'post_type' => 'message',
'post_status' => 'pending',
'tax_input' => $custom_tax
);
$post_id = wp_insert_post($public_post);
}

ACF form post woocommerce product

i am developing a multivendor shop and i want the vendors to post products from a Template page. i am using Advance custom fields to achieve this functionality.
What i did by far is to create the page template and managed to display the form but i have some issue to validate the fields with the Product. i might need to create some functionalities ?
<?php
/**
* The template for displaying all pages.
* Template Name: Add Product Vendor
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* #package Bober
*/
?>
<?php
acf_form_head();
get_header();
?>
<div id="content">
<?php
global $woocommerce;
acf_form(array(
$post_title = 'field_5a60022b402e2',
$post_categ = 'field_5a60028e402e3',
$post_descrip = 'field_5a600384402e4',
$post_img = 'field_5a6005e1402e7',
$post_price = 'field_5a61207ce5226',
/*'post_title' =>true,
'post_content' => true,*/
'uploader' => 'basic',
'post_id' => 'new_post',
'fields' => array($post_title, $post_descrip, $post_categ,$post_price, $post_img),
'new_post' => array(
'post_status' => 'draft',
'post_type' =>'product',
),
/*'fields' => array('field_5a60022b402e2', 'field_5a60028e402e3', 'field_5a600384402e4', 'field_5a6005e1402e7'),*/
'submit_value' => 'Add product'
));
?>
</div>
<?php get_footer(); ?>
At this point i was able to asign the title of the product and the content of by using the code below based on ACF form documentation.
'post_title' =>true,
'post_content' => true,
How do i assign the Title value, the description value, price value and image to the product post ? I don't necesary look for someone to provide me a code to replace, i want to know how to do it, give me some ideas, or where to read on how to do it.
Thank you in advance!
First, do an in-depth read of how acf_form() works.
The acf_form() code for adding a product in woocommerce could look like this:
$options = array(
'post_id' => 'new_post',
'post_title' => true,
'post_content' => true,
'new_post' => array(
'post_type' => 'product',
'post_status' => 'draft'
),
'field_groups' => [$field_group_id],
'form' => true,
'return' => '%post_url%', // so they could be redirected to the product page in a draft state - i imagine?!
'html_submit_button' => '<input type="submit" value="%s" />',
'updated_message' => 'Product Created',
'submit_value' => 'Submit Product'
);
acf_form($options);
Regarding the featured image of the product, create an image field and use the code below to sync the field with the featured image. You can read more about this by checking the ACF API reference for acf/update_value
add_filter('acf/update_value/name=featured_image', function ($value, $post_id, $field) {
if ($value != '') {
update_post_meta($post_id, '_thumbnail_id', $value);
} else {
delete_post_thumbnail($post_id);
}
return $value;
}, 10, 3);

Wordpress Recent Posts/Projects

Hi I have created my own custom post type within Wordpress to contain projects that i can call via my theme files.
I am new to creating my own themes. I currently am using the following code in my single.php file to call in related articles based on the category of the blog post.
<?php
// Default arguments
$args = array(
'posts_per_page' => 3, // How many items to display
'post__not_in' => array( get_the_ID() ), // Exclude current post
'no_found_rows' => true, // We don't ned pagination so this speeds up the query
);
// Check for current post category and add tax_query to the query arguments
$cats = wp_get_post_terms( get_the_ID(), 'category' );
$cats_ids = array();
foreach( $cats as $wpex_related_cat ) {
$cats_ids[] = $wpex_related_cat->term_id;
}
if ( ! empty( $cats_ids ) ) {
$args['category__in'] = $cats_ids;
}
// Query posts
$wpex_query = new wp_query( $args );
// Loop through posts
foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>
<div class="col-md-4 related-post">
<?php the_post_thumbnail('large'); ?>
<?php the_title(); ?>
</div>
<?php
// End loop
endforeach;
// Reset post data
wp_reset_postdata(); ?>
In my new post type "projects" i would like to call in related projects. Which im assuming would be very similar code except i need to stop it looking for posts and instead look for my projects.
Here is my code for new post type:
// Projects
add_action( 'init', 'create_post_type' );
add_post_type_support( 'bw_projects', 'thumbnail' );
add_post_type_support( 'bw_projects', 'custom-fields' );
function create_post_type() {
register_post_type( 'bw_projects',
array(
'labels' => array(
'name' => __( 'Projects' ),
'singular_name' => __( 'Projects' )
),
'public' => true,
'has_archive' => true,
'taxonomies' => array( 'category','post_tag'),
)
);
}
What would i need to change in my first code snippet in order to look for bw_projects and not look for 'posts' anymore. I tried playing around and changing certain lines myself but i caused more issues and stopped the page loading. Is this even right i can use the same code, slightly altered or would i need something completely different?
Thanks in advance.
You can get any post type that you require using get_posts();
<?php $args = array(
'posts_per_page' => 5,
'offset' => 0,
'category' => '',
'category_name' => '',
'orderby' => 'date',
'order' => 'DESC',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'projects',
'post_mime_type' => '',
'post_parent' => '',
'author' => '',
'author_name' => '',
'post_status' => 'publish',
'suppress_filters' => true
);
$posts_array = get_posts( $args ); ?>
Simply set the 'post_type' argument to that of you custom post type, to get only these posts. You can also set the number of post, and filter by category etc.
You can find more info in the codex.
Alternatively, if you wanted to keep something similar to your existing code you could try using 'pre_get_posts' to filter the query to just your projects. However you'd need to remember to add / remove this filter so it only operates on the queries that need it.
To display the posts you can use a simple foreach to churn them out. You#d obviously want to do some sort of styling to get the layout correct:
$args = array("posts_per_page" => 10, "orderby" => "comment_count");
$posts_array = get_posts($args);
foreach($posts_array as $post)
{
echo "<h1>" . $post->post_title . "</h1><br>";
echo "<p>" . $post->post_content . "</p><br>";
}
Or a really concise way of doing all of the above would be something like:
$args = array("posts_per_page" => 5, "post_type" => "projects");
$posts_array = get_posts($args);
foreach($posts_array as $post)
{
echo "<h1>" . $post->post_title . "</h1><br>";
echo "<p>" . $post->post_content . "</p><br>";
}

Wordpress Meta Box plugin, retrieving image url from custom post type

Having a bit of bother with the Wordpress Meta Box plugin, specifically with retrieving an image url from an image added to a custom post type.
I'm creating meta boxes in a custom plugin, like so:
add_filter( 'rwmb_meta_boxes', 'xxx_meta_register_meta_boxes' );
function xxx_meta_register_meta_boxes( $meta_boxes )
{
$prefix = 'xxx_meta_';
$meta_boxes[] = array(
'title' => esc_html__( 'Retailer Information', '' ),
'id' => 'advanced',
'post_types' => array( 'xxx_retailers' ),
'autosave' => true,
'fields' => array(
// PLUPLOAD IMAGE UPLOAD (WP 3.3+)
array(
'name' => esc_html__( 'Retailer Logo', '' ),
'id' => "{$prefix}plupload",
'type' => 'plupload_image',
'max_file_uploads' => 1,
),
// URL
array(
'name' => esc_html__( 'Link', '' ),
'id' => "{$prefix}url",
'desc' => esc_html__( 'Clicking the retailer logo will take the user to this URL', '' ),
'type' => 'url',
'std' => 'xxx',
),
)
);
return $meta_boxes;
}
So far so good, these boxes are relevant to a custom post type 'xxx_retailers'.
The problem comes with retrieving this data. I want to display my retailers in a widget. I've chopped and changed another piece of code I've used previously, but it's not returning the image URL, just the ID. Unfortunately I don't know enough php to figure out why.
// Create Retailers Widget
// Create the widget
class Retailers_Widget extends WP_Widget {
function __construct() {
parent::__construct(
// base ID of the widget
'retailers_widget',
// name of the widget
__('XXX Retailers List', '' ),
// widget options
array (
'description' => __( 'Shows a list of retailer logos', '' )
)
);
}
function widget( $args, $instance ) {
// kick things off
extract( $args );
echo $before_widget;
echo $before_title . 'Retailers' . $after_title;
// Pull through Retailers
$xxxretailers = get_posts(array(
'post_type' => 'xxx_retailers',
'orderby' => 'title',
'order' => 'asc',
));
// Display for each Retailer
foreach ($xxxretailers as $xxxretailer) {
$custom = get_post_custom($xxxretailer->ID);
$meta_ret_img = $custom["xxx_meta_plupload"][0];
$meta_ret_url = $custom["xxx_meta_url"][0];
// Display Retailers
echo "<li><a href='{$meta_ret_url}'><img src='{$meta_ret_img}' /></a></li>";
}
}
};
// Register widget
function register_retailers_widget() {
register_widget( 'Retailers_Widget' );
}
add_action( 'widgets_init', 'register_retailers_widget' );
The URLs are coming through correctly, so I know this is a problem with the line
$meta_ret_img = $custom["xxx_meta_plupload"][0];
But I can't figure out how to get the image URL from the data I presume is stored as an array. Any ideas?
Edit:
I should have mentioned, in a single post I can get a single image with:
$images = rwmb_meta( 'xxx_meta_plupload', 'size=medium' );
if ( !empty( $images ) ) {
foreach ( $images as $image ) {
echo "<img src='{$image['url']}' />";
}
}
But I want to show images from all my retailers post types, to create a list of logos.
Replace this statement:
$meta_ret_img = $custom["xxx_meta_plupload"][0];
with this:
$meta_ret_img_array = wp_get_attachment_image_src($custom["xxx_meta_plupload"][0]);
$meta_ret_img = $meta_ret_img_array[0];
also please remove all these curly braces from src and href attributes from your code.
if you are interested in any particular size of the image, then see the official document of wp_get_attachment_image_src() function here.
For e.g. for medium size image you can write it as:
wp_get_attachment_image_src($custom["xxx_meta_plupload"][0], 'medium');

Categories