WordPress run php code into the_content loop - php

I'm learning PHP and WordPress development, so I assumed that maybe here I'll find the answer or a tip.
I've restriced the_content based on user role. After the end of the_content I'd like to display button whitch is unique to the specific post. So here is the code which display that:
function displaycontent($content) {
if(is_singular( 'custom_post_type' )) {
$aftercontent = 'I Want To Add Code Here';
$fullcontent = $content . $aftercontent;
} else {
$fullcontent = $content;
}
return $fullcontent;
}
add_filter('the_content', 'displaycontent');
And I'd like to insert code below into the underlined place above:
<?php
$post = $wp_query->post;
$group_id = get_field( 'link_number' , $post->ID );
if( $group_id ) {
echo do_shortcode( '[checkout_button class="button" level="' . $group_id . '" text="Order"]' );
}
?>
How can I do that?

It's probably better to create a custom shortcode for this. If you change how the_content works, it will be global, everywhere.
Note:
This code is completely untested and put together after 5 min of Googling, so if somehting is wrong, feel free to comment and I'll amend it. It should be fairly close and is mostly for explaining the concept instead of a pure copy/paste solution
Register a new shortcode:
add_shortcode('my_awesome_content', 'my_awesome_content_func');
Create the callback function:
Here we've added $atts which will contain our attribute (the post id):
function my_awesome_content_func($atts = [])
{
$postId = $atts['postid'] ?? null;
if ($postId === null) {
// We got no id so let's bail
return null;
}
$post = get_post($postId);
if (!$post) {
// We didn't find any post with the id so again, let's bail
return null;
}
$group_id = get_field( 'link_number' , $post->ID );
$content = $post->content;
if( $group_id ) {
$content .= do_shortcode( '[checkout_button class="button" level="' . $group_id . '" text="Order"]' );
}
return $content;
}
Usage:
Now you should be able to call it like this:
echo do_shortcode('[my_awesome_content postid="' . $post->ID . '"]');

You can just embed you code below in the above filter with some modifications:
function displaycontent($content) {
if (is_singular('custom_post_type')) {
$post_id = get_queried_object_id();
$group_id = get_field('link_number', $post_id);
$aftercontent = '';
if ($group_id)
$aftercontent = do_shortcode('[checkout_button class="button" level="'.$group_id. '" text="Order"]');
$fullcontent = $content.$aftercontent;
} else {
$fullcontent = $content;
}
return $fullcontent;
}
add_filter('the_content', 'displaycontent');

OK, thanks everyone, I Got it! Here is the code if anyone would have same problem:
function displaycontent($content) {
if(is_singular( 'custom_post_type' )) {
$group_id = get_field('link_number');
$aftercontent = do_shortcode( '[checkout_button class="button" level="' . $group_id . '" text="Order"]' );
$fullcontent = $beforecontent . $content . $aftercontent;
} else {
$fullcontent = $content;
}
return $fullcontent;
}
add_filter('the_content', 'displaycontent');

Related

Ajax filter not returning page content with filter

I have a special function on some of my pages that returns a modified embed code. It works great:
if (/*is_page() &&*/ has_category('Krajské zprávy')) {
/* get subtitle */
$subtitle = apply_filters( 'plugins/wp_subtitle/get_subtitle', '', array(
) );
if ((strpos($subtitle , 'kraj') == false) && (strpos($subtitle , 'Praha') == false) && (strpos($subtitle , 'Vysočina') == false)) {
$subtitle = "Všechny kraje";
};
/* get page id with embed code */
$id_short = 357;
$tag_id = array (
'Ovzduší' => 357
);
foreach ($tag_id as $k => $v) {
if (has_tag($k)) {$id_short = $v;}
}
/* get embed code & replace */
$acf_kod = get_field('embed_kod', $id_short /*,false*/);
$replace_sub = "<param name='filter' value='Parameters.Kraj=" . $subtitle . "'>";
preg_match_all('/<param [^>]*>/', $acf_kod, $matches);
$m_1 = $matches[0][0]; $m_2 = $matches[0][1];
$pos = strpos( $acf_kod, $m_1) + strlen( $m_1 );
if (strpos($acf_kod,$m_2)-(strpos($acf_kod,$m_1)+strlen($m_1))<2) {
$before = substr ($acf_kod, 0, $pos);
$after = substr( $acf_kod, $pos, strlen( $acf_kod ) );
$whole = $before . $replace_sub . $after;
$content = $whole .'<!--more-->' . $content;
};
/*echo $whole;*/
};
return $content;
};
add_filter('the_content', 'add_embed_parameter');
However, I also have a filter on my site that filters pages by categories and tags and returns them via Ajax. That, too, works just fine - but only with "standard pages" that don't use the code above. For the pages that do, it returns nothing.
This is a snippet of the php code that is used by the filter:
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
/*$content = get_post_field( 'post_content', get_the_ID() );*/
$content = get_the_content (/*get_the_ID()*/);
$content_parts = get_extended( $content );
echo '<h2>' . $query->post->post_title . '</h2>',
$content/*$content_parts['main'] /*'<p>' . $query->post->post_excerpt . '</p>'*/;
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
This is the whole AJAX thing (it's not mine, I'm using the tutorial here):
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
Any idea where the problem might be? Many thanks!

Insert custom field value before content

I have a custom meta field that I would like to insert in the_content automatically so that my AMP plugin can render the custom field value in the same way as the_content.
Currently I am using this code to display it:
<?php $video_value = get_post_meta( get_the_ID(), '_video', true ); ?>
<?php if ( ! empty( $video_value ) ) {?>
<div class="video-container"><?php echo $video_value; ?></div>
<?php } else { ?>
<?php the_post_thumbnail(); ?>
<?php } ?>
But I would like the $video_value to be inserted automatically before the_content.
You can use the the_content filter to do this. You can read more about it on the WordPress developer site.
But the code could be looking something like this:
function my_custom_content_filter($content){
global $post;
$video_value = get_post_meta($post->ID, '_video', true);
if($video_value){
return '<div class="video-container">' . $video_value . '</div>' . $content;
}else{
return get_the_post_thumbnail($post->ID) . $content;
}
}
add_filter('the_content', 'my_custom_content_filter');
And you can add this code in you functions.php file.
Note This filter only works on the_content() and not get_the_content()
You can do something like this -
and add the conditions that you want -
You might need to access Global $post to get the meta value
function custom_weird_name_before_after($content) {
if(is_page() || is_single() || $yourOwnConditions == true) {
$beforecontent = 'This line will go before the content - populate with whatever.';
$aftercontent = 'This will come after the content - makes sense right?';
$fullcontent = $beforecontent . $content . $aftercontent;
} else {
$fullcontent = $content;
}
return $fullcontent;
}
add_filter('the_content', 'custom_weird_name_before_after');
You can add this in functions.php

Only Show text on Child Post wordpress

I want to show google ad on my wordpress attachment page which is child page to post on wordpress. I just want to show this ad only child post/page not on parent post. i want to show in the end of content so i tried this code
function wpdev_before_after($content) {
global $post;
if ($post->post_parent)
$aftercontent = 'Ad code here';
$fullcontent =$content . $aftercontent;
return $fullcontent;
}
add_filter('the_content','wpdev_before_after');
Above code show ad on both pages parent and child, I also tried this code in this way
function wpdev_before_after($content) {
global $post;
if ($post->post_parent) {
$aftercontent = 'code here';
$fullcontent =$content . $aftercontent;
}
return $fullcontent;
}
add_filter('the_content','wpdev_before_after');
If i use this code on parent page/post content not show . please help me, i hope i you understand what i want to say.
try this:
function wpdev_before_after($content) {
global $post;
if(is_singular() && $post->post_parent > 0) {
$aftercontent = 'code here';
$fullcontent =$content . $aftercontent;
return $fullcontent;
}
else
return $content;
}
add_filter('the_content','wpdev_before_after', 9999);
Thanks to #Tarun Mahashwari for help me to get working code.
Here is working code for posts and child posts.
function wpdev_before_after($content) { global $post; if ($post->post_parent) { $aftercontent = 'code here'; $fullcontent =$content . $aftercontent; return $fullcontent; } else return $content; } add_filter('the_content','wpdev_before_after');
May be this code work for pages and child pages provided by #Tarun Mahashwari
function wpdev_before_after($content) {
global $post;
if(is_page() && $post->post_parent > 0) {
$aftercontent = 'code here';
$fullcontent =$content . $aftercontent;
return $fullcontent;
}
else
return $content;
}
add_filter('the_content','wpdev_before_after', 9999);

Looping through ACF in custom post types using functions in php to display the values in page. foreach quits working when placed in the function

I created this code to display the location from ACF that matches part of the URL and it works as expected.
<?php
$myurl= htmlspecialchars($_SERVER["REQUEST_URI"]);
$myexplodes = ( explode ('/', $myurl) );
$posts = get_posts(array(
'post_type' => 'my_vars',
));
if( $posts ){
foreach( $posts as $post ){
$value = get_field( "location" );
//echo get_field( "location" );
if( $value == $myexplodes[1]) {
echo '<h1>' . $value . ' :this is location</h1>';
}
else {
}
}
}
?>
But when I try to place this code into a function nothing is displayed when I call it.
function local (){
if( $posts ){
foreach( $posts as $post ){
$value = get_field( "location" );
//echo get_field( "location" );
if( $value == $myexplodes[1]) {
echo '<h1>' . $value . ' :this is location</h1>';
}
else {
}
}
}
}
I suspected that it is a scope problem with the vars but I have tried to make the vars global but had no luck.
The first one probably works because $post is a WordPress global variable, so I advise to use another variable name in your foreach.
For the thing that you want to do you should use also the post id in the get_field function call:
$value = get_field( "location", $article->ID );

Function output not appearing in div

This is my first try at php.
Trying to create a custom shortcode in wordpress to call custom metadata and put it inside a page content. It worked fine without the
function wpsl_staff() {
echo '<div class="staff">' .wpsl_get_staff(). '</div>';
function wpsl_get_staff() {
and with the shortcode being
add_shortcode( 'wpsl_staff', 'wpsl_get_staff' );
The output was correct but the output appeared at the top of the page above all other content and when I inspected in the browser it had no div or class id and just appeared as text. How do I wrap this in a div and give id so it sits properly on the content page (It should display between 2 images and under another shortcode) I have managed to give it a class id previously and get it to appear in a div but the output still appears at the top of the page above the images and other shortcode.
<?php
function wpsl_get_staff() {
global $post;
$queried_object = get_queried_object();{
$Manager = get_post_meta( $queried_object->ID, 'wpsl_Manager', true );
if (!empty( $Manager )) return 'Manager : ' .$Manager . "<br>";
else {}
$Assitant = get_post_meta( $queried_object->ID, 'wpsl_Assistant_Manager', true );
if (!empty( $Assistant )) return 'Assistant Manager : ' .$assistant . "<br>";
else {}
$Agent = get_post_meta( $queried_object->ID, 'wpsl_Agent', true );
if (!empty( $Agent )) return 'Agent : ' .$Agent . "<br>";
else {}
}
}
function wpsl_staff() {
echo '<div class="staff">' .wpsl_get_staff(). '</div>';
}
add_shortcode( 'wpsl_staff', 'wpsl_dio_staff' );
Thanks
Toca
Shortcode functions are supposed to return the result, not directly output it.
function wpsl_staff() {
return '<div class="staff">' .wpsl_get_staff(). '</div>';
}
Edit: You can only return one value from a function - so if your wpsl_get_staff is supposed to return data for all three types, then you need to assemble that data into a string variable first, and then return that at the end of the function - something like this:
function wpsl_get_staff() {
global $post;
$queried_object = get_queried_object();
$output = '';
$Manager = get_post_meta( $queried_object->ID, 'wpsl_Manager', true );
if (!empty( $Manager )) {
$output .= 'Manager : ' .$Manager . "<br>";
}
$Assitant = get_post_meta( $queried_object->ID, 'wpsl_Assistant_Manager', true );
if (!empty( $Assistant )) {
$output .= 'Assistant Manager : ' .$assistant . "<br>";
}
$Agent = get_post_meta( $queried_object->ID, 'wpsl_Agent', true );
if (!empty( $Agent )) {
$output .= 'Agent : ' .$Agent . "<br>";
}
return $output;
}

Categories