How can I add a css class to my example php code - php

Idd like to add a class within the output of this piece of php code
function acf_esg_tax_field_loc( $atts, $content = null ) {
$a = shortcode_atts(array('post_id' => "1"), $atts);
$term = get_field( "field_56cb3d84cf32a", $a['post_id'] );
echo $term->name;
}
add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );
The code is used in my Wordpress functions php to generate a shortcode.
It should be something like this
function acf_esg_tax_field_loc( $atts, $content = null ) {
$a = shortcode_atts(array('post_id' => "1"), $atts);
$term = get_field( "field_56cb3d84cf32a", $a['post_id'] );
echo '<div class="OutputClass" >';
echo $term->name;
echo '</div>';
}
add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );
Unfortunatly this does not work.
Can you please help?

As the WordPress Code Reference states.
Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce expected side effects from the call, since you cannot control when and where they are called from.
So first change it from echo to one return.
You could define a variable, concatenate to it and finally return it.
Result:
function acf_esg_tax_field_loc( $atts, $content = null ) {
$a = shortcode_atts(array('post_id' => "1"), $atts);
$term = get_field( "field_56cb3d84cf32a", $a['post_id'] );
$sR = '<div class="OutputClass" >';
$sR .= $term->name;
$sR .= '</div>';
return $sR;
}
add_shortcode( 'acfesgtax_loc', 'acf_esg_tax_field_loc' );

If the class is always the same and thus could be hardcoded, then you are very close. Only one echo will be outputted, so concatenate it:
echo '<div class="OutputClass" >'.$term->name.'</div>';
If it's dynamic and you need to get the class name somewhere and pass it along, then that's a whole different story.

Related

Wordpress shortcode php array to text in a text block

I am beginning to make a site in wordpress (so no php or html experience). I want to generate textlist from a mysql column into a text block.
I have made the php code for the shortcode below which returns an array which now displays in the textblock as "Array" instead of a list of strings.
If i just print the values they appear on the head of the page.
What are the next steps I need to do/look for. I can't find it because I probably do not know the correct search terms. My guess is something with HTML.
<?php
function location_marker_shortcode( $atts ) {
$a = shortcode_atts( array(
'mapnumber' => 'world'
), $atts );
global $wpdb;
//select databases (the 84 part should be the input of the shortcode)
$marker_labels = $wpdb->get_col('SELECT label FROM wp_mapsvg_database_84');
foreach ( $marker_labels as $marker_label )
{
//print labels
echo $marker_label;
}
return $marker_labels;
}
//add shortcode to wordpress
add_shortcode( 'matthijs', 'location_marker_shortcode' );
?>
I have now this code which gives me a list exactly what i want but not in the "paragraph block" in wordpress where my shortcode is situated.
<?php
function location_marker_shortcode( $atts ) {
$a = shortcode_atts( array(
'mapnumber' => 'world'
), $atts );
global $wpdb;
//select databases (the 84 part should be the input of the shortcode)
$marker_labels = $wpdb->get_col('SELECT label FROM wp_mapsvg_database_84');
foreach ( $marker_labels as $marker_label )
{
echo '<li>'. $marker_label.'</li>';
}
}
//add shortcode to wordpress
add_shortcode( 'matthijs', 'location_marker_shortcode' );
?>
I'm not 100% sure what you're trying to accomplish, but try this. You don't want to echo out all the values as you're looping through them. Concatenate everything in a variable and then return the entire string at the end of your shortcode. This should generate an unordered list.
<?php
function location_marker_shortcode( $atts ) {
$a = shortcode_atts( array(
'mapnumber' => 'world'
), $atts );
global $wpdb;
//select databases (the 84 part should be the input of the shortcode)
$marker_labels = $wpdb->get_col('SELECT label FROM wp_mapsvg_database_84');
$output = '<ul>';
foreach ( $marker_labels as $marker_label )
{
$output .= '<li>' . $marker_label . '</li>';
}
$output .= '</ul>';
return $ouput;
}
//add shortcode to wordpress
add_shortcode( 'matthijs', 'location_marker_shortcode' );
?>

How to pull variable output from add_action() with do_action() or is there another method?

May look a very basic thing to the majority here but i'm stuck.
Here is the PHP code that is in my WP functions file (functions.php):
add_action( 'AHEE_event_details_after_the_content', 'my_event_registration_count' );
function my_event_registration_count( $post ) {
$event_obj = $post->EE_Event;
$html = '';
if ( $event_obj instanceof EE_Event ){
$reg_count = EEM_Event::instance()->count_related(
$event_obj,
'Registration',
array(
array(
'STS_ID' => array(
'NOT_IN',
array(
EEM_Registration::status_id_cancelled
)
)
)
)
);
$html .= '<strong>';
$html .= $reg_count;
$html .= ' of ';
$html .= $event_obj->total_available_spaces();
$html .= ' attendees total</strong>';
}
echo $html;
}
I'm trying to get $html output with:
<?php do_action( 'my_event_registration_count', $html ); ?>
Supposed to give me number of registered event attendees. I need to get this number to my WP front page. Nothing.. Also tried with $reg_count. Is this ting supposed to be global? I'm thankful for all the help i can get.
The correct way to write functions with an output in WordPress is with add_filter / apply_filters. It's otherwise the same as add_action / do_action.
Reference:
https://developer.wordpress.org/reference/functions/add_filter/
https://developer.wordpress.org/reference/functions/apply_filters/

Displaying post titles in a specific category in a shortcode (wordPress)

Trying to write my first short-code that displays all post-titles in a specific Category. But it is not displaying the actual results, just the short code.
Here is what I have so far in my child theme's functions.php file:
function posts_in_cat() {
echo '<ul>';
query_posts('cat=3'); while (have_posts()) : the_post();
echo ('<li>' . the_title() . '</li>');
endwhile;
wp_reset_query();
echo '</ul>';
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );
And then I am calling the short code, like so [display_posts_in_cat].
Any help would be greatly appreciated as I try and learn this.
EDIT: I have gotten it to display but the link itself is being echo-ed in front of the title in text. Also, it is not displaying more than 10 of the titles and I want it to display them all. Any ideas...?? Thanks.
First and foremost, avoid using query_posts() – it's inefficient. Check out this SO answer for the skinny.
Additionally, shortcodes shouldn't make use of echo statements. Shortcodes only return text. Put simply, WordPress has PHP internally that says "when this specific shortcode is entered into the editor, replace it with the text returned from this function." Using echo causes you to immediately print those statements to the screen, rather than returning to WordPress so that it can continue with its regular process. More on the WP Codex.
And, finally, shortcode functions require $atts as a parameter.
So, with all that said, here's how I would rewrite your function:
<?php
function posts_in_cat( $atts ) {
$atts = shortcode_atts( array(
'cat' => '',
), $atts );
if ( empty( $atts['cat'] ) ) {
// If category provided, exit early
return;
}
$args = array(
'category' => $atts['cat'],
// Disable pagination
'posts_per_page' => -1
);
$posts_list = get_posts( $args );
if ( empty( $posts_list) ) {
// If no posts, exit early
return;
}
$opening_tag = '<ul>';
$closing_tag = '</ul>';
$post_content = '';
foreach ( $posts_list as $post_cat ) {
$post_content .= '<li>' . esc_html( get_the_title( $post_cat->ID ) ) . '</li>';
}
return $opening_tag . $post_content . $closing_tag;
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );
I'm just adding all of the content you were echoing into a handful of variables, and then returning them, concatenated, at the end. Also, I added in an if statement to exit early if there aren't any posts in the category. That way you don't have an empty <ul> element cluttering up the page.
I've also escaped the outputs, which you can read about on the Codex.
Please try this:
function posts_in_cat() { ?>
<ul class="posts">
<?php query_posts('cat=3&showposts=50'); while (have_posts()) : the_post();
?>
<li><a href='<?php the_permalink() ?>'><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul>
<?php
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );

Return ACF field as a Shortcode using Wordpress Functions.php file

How do I use an Advanced Custom Field as a Shortcode. Ive used the following code in the Wordpress functions.php file but no luck.
Here is my Code:
function location_date_func( $atts ){
return "<?php the_field('location_date', 658); ?>";
}
add_shortcode( 'location_date', 'location_date_func' );
You need to register the shortcode properly, and make it return the data to display, not return a string with php code in it:
function location_date_func( $atts ){
//return string, dont echo it, so use get_field, not the_field
return get_field('location_date', 658);
}
//create function to register shortcode
function register_shortcodes(){
add_shortcode( 'location_date', 'location_date_func' );
}
// hook register function into wordpress init
add_action( 'init', 'register_shortcodes');
Or if you are using php 5.3+, you can use anonomous functions to acheive the same result:
add_action('init', function(){
add_shortcode('location_date', function(){
return get_field('location_date', 658);
});
});
Got it to work!
function location_date_func( $atts ){
return apply_filters( 'the_content', get_post_field( 'location_details', 658 ) );
}
add_shortcode( 'location_date_sc', 'location_date_func' );
If you want to return the value of an ACF field using the_field(), there is already a built in shortcode to do that.
[acf field="location_date" post_id="658"]
If you would like to reproduce it using the [location_date] shortcode, you need to use get_field() to return rather than echo the value. Syntax-wise, the only problem with your code is that you do not need the double quotes or <?php tags, since it should already be inside a PHP block. It will be functionally the same as the [acf] shortcode, but does not accept the post_id argument. This example will be hard coded to post ID 658 unless you modify it to accept an ID as part of the $atts or use the global $post;
function location_date_func( $atts ){
return get_field( 'location_date', 658 );
}
add_shortcode( 'location_date', 'location_date_func' );
add_shortcode('location_start_your_application_group', 'start_your_application_group');
function start_your_application_group() {
$start_your_application_group = '';
$start_your_application_group .= '<section class="start-your-application">';
if ( have_rows( 'start_your_application_group', 'option' ) ) :
while ( have_rows( 'start_your_application_group', 'option' ) ) : the_row();
$heading = get_sub_field( 'heading' );
$content = get_sub_field( 'content' );
if ( $heading !== '' ) {
$start_your_application_group .= '<h3 class="start-your-application__heading">' . $heading . '</h3>';
}
if ( $content !== '' ) {
$start_your_application_group .= '<div class="start-your-application__content">' . $content . '</div>';
}
$image = get_sub_field( 'image' );
if ( $image ) {
$start_your_application_group .= '<div class="start-your-application__image-container"><img class="start-your-application__image" src="' . $image['url'] .'" alt="' . $image['alt'] . '" /></div>';
}
endwhile;
endif;
$start_your_application_group .= '</section>';
return $start_your_application_group;
}

Can't get an echo to do what I want in Wordpress plugin

So I'm trying to write a new plugin since I haven't been able to find one that does exactly what I want with the extensibility that I desire. The goal of the plugin is to be able to use a simple shortcode to display an image slider that automatically populates with your blog's latest posts.
I've got the basic plugin files ready and the shortcode implemented and tested. I had a snafu solved yesterday on SO but the solution highlighted a new problem. Here's the code:
function slyd( $category, $slydcount ) {
global $post;
$tmp_post = $post; // Create $tmp_post to empty $post once Slyd is done with it
$args = array(
'category' => $category,
'numberposts' => $slydcount
);
$slydposts = get_posts( $args );
foreach( $slydposts as $post ) : setup_postdata($post);
$post_title = get_the_title(); // Get the post's title
$post_content = get_the_content(); // Get the post's content - will write code to get excerpt later
$post_thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' ); // Get the post's featured image's src
$post_permalink = get_permalink(); // Get the post's permalink
echo '<h2>' . $post_title . '</h2>'
. '<p>' . $post_content . '</p>'
. '<p>' . $post_thumb . '</p>';
endforeach;
$post = $tmp_post; // Empty $post once Slyd is done with it
}
// Create the shortcode
function slyd_shortcode( $atts ) {
// $atts ::= array of attributes
// examples: [slyd]
// [slyd category='slide']
// [slyd slydcount='5']
// [slyd theme='default']
/* Retrieve attributes set by the shortcode and set defaults for
unregistered attributes. */
extract( shortcode_atts( array(
'category' => 'slyd', // Which category(s) to display posts from
'slydcount' => '5', // How many Slyds to display
'theme' => 'default' // Which Slyd theme to use
), $atts ) );
return "<p>category = {$category}, count = {$slydcount}</p>"
. slyd( $category, $slydcount );
}
add_shortcode( 'slyd', 'slyd_shortcode' );
The issue is in the foreach loop in function slyd();. I was originally using a return where the echo is now to put the result on the screen. That worked to display the first post but it would, of course, escape the function. I need it to cycle through and display all of the posts.
From researching the PHP documentation I found that I could use print in place of echo or return but it's giving me the same result as echo. What's happening is the code seems to be executing twice. It places itself where it needs to be the first time, then it also echoes to the browser and places it just below the head of the page.
I suppose my question is whether there's an alternative to return, echo, or print that would solve my problem?
Thanks in advance.
Now I'm trying to get the plugin to pull in the blog's latest posts but I'm running into a bit of a snafu. When I use the_title() and the_permalink() they display outside of the code I'm trying to contain them in. Further, the_content() is displaying once with the_permalink() and the_title() and then a second time where it's supposed to.
You can see the behavior here.
return is what you want in this case. You want to return a value (i.e. html code) from the slyd function so you can use it (in this case append it) in the slyd_shortcode function. However, you need to first collect all output into an additional variable ($ret below), and then return that value:
function slyd( $category, $slydcount ) {
global $post;
$tmp_post = $post;
$args = array(
'category' => $category,
'numberposts' => $slydcount
);
$slydposts = get_posts( $args );
$ret = '';
foreach( $slydposts as $post ) {
setup_postdata($post);
$post_title = get_the_title();
$post_content = get_the_content();
$post_thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
$post_permalink = get_permalink();
$ret .= '<h2>' . $post_title . '</h2>'
. '<p>' . $post_content . '</p>'
. '<p>' . $post_thumb . '</p>';
}
$post = $tmp_post;
return $ret;
}
As you see you should first initialize the $ret variable with an empty string, then append to it on each iteration of the foreach loop. return is used to return the whole string after the loop.

Categories