Simple shortcode $id+$title with small html - php

I have a simple need to put a shortcode at the end of my articles on wordpress with the post id and post title.
I want to add a (ref:) in front of $id and enclose it all in h4
the desired result look like this
<h4 ref: 123 this is my first post <h4>
I'm having a hard time getting the logic of how to do it
my shortcode
function post_id_title( ){
$id = get_the_ID();
$title = get_the_title();
$result = $id . $title ;
return $result;
}
add_shortcode( 'page_title', 'post_id_title' );

Try this since you got the hardest part right.
function post_id_title( ){
$id = get_the_ID();
$title = get_the_title();
$result = "<h4>ref: $id $title</h4>";
return $result;
}
add_shortcode( 'page_title', 'post_id_title' );

Related

WordPress run php code into the_content loop

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');

Extract shortcode content from another post

I have a shortcode [Mark] which only used as a marker for texts. And another shortcode [MarkExt] for extracting content of Marker based on the post id.
[Mark label="mrk"]Some text here[/Mark]
What I need to do is that when I invoke
[MarkExt label="mrk" id=10]
is to get the text that is enclosed by [Mark] of label mrk specified in the post id.
How can I get the [Mark ] content?
EDIT: Apologies on incomplete post . What I've done so far was
For [Mark]
function mark_shortcode($atts,$content = null){
return $content;
}
add_shortcode( 'Mark', 'mark_shortcode' );
And for [MarkExt]
function extract_shortcode($atts,$content = null){
$label = $atts['label'];
$pid = $atts['id'];
}
add_shortcode( 'MarkExt', 'extract_shortcode' );
Add following code to functions.php or plugin file.
function mark_caption_shortcode( $atts, $content = null ) {
//$content is Some text here
return $content;
}
global $mark_content;
$mark_content = add_shortcode( 'mark', 'mark_caption_shortcode' );
function extract_shortcode($atts,$content = null){
global $mark_content;
//here you will get content
$label = $atts['label'];
$pid = $atts['id'];
}
add_shortcode( 'MarkExt', 'extract_shortcode' );

How to strip all visual composer shortcode/tags from wordpress's post_content fetched with custom query

I am working on a web-service(API) where i am fetching result WP_query() function and parse that in JSON format. which will further use in android application.
The problem is the post_content i am getting with query is composed by visual composer and the whole content is in form of such tags like
[VC_ROW][/VC_ROW][VC_COLUMN]some text[/VC_COLUMN] etc.
I want to remove/strip all these shortcode from the content and retrieve only plain text from it. Is there any visual composer function through which i can achieve this thing
<?php
require('../../../wp-load.php');
require_once(ABSPATH . 'wp-includes/functions.php');
require_once(ABSPATH . 'wp-includes/shortcodes.php');
header('Content-Type: application/json');
$post_name = $_REQUEST['page'];
if($post_name!=''){
if($post_name=='services') {
$args = array(
'post_parent' => $page['services']['id'],
'post_type' => 'page',
'post_status' => 'published'
);
$posts = get_children($args);
foreach($posts as $po){
$services_array[] = array('id'=>$po->ID,'title'=>$po->post_title,'image'=>get_post_meta($po->ID, 'webservice_page_image',true),'description'=>preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $po->post_content));
}
$post = array(
'status'=>'ok',
'services'=>$services_array
);
echo json_encode($post);
}
}
?>
I want to remove/strip all these shortcode from the content and retrieve only plain text from it.
Solution that worked for me:
$content = strip_tags( do_shortcode( $post->post_content ) );
do_shortcode triggers all visual composer shortcodes and thus returns html+text;
strip_tags removes all html tags and returns plain text.
Here, you can try and easily add some short codes in array that you needs and also you can remove all shortcodes via below code.
$the_content = '[VC_ROW][VC_COLUMN]some text1[/VC_COLUMN] etc.[/VC_ROW][VC_COLUMN_INNTER width="1/3"][/VC_COLUMN_INNTER]';
$shortcode_tags = array('VC_COLUMN_INNTER');
$values = array_values( $shortcode_tags );
$exclude_codes = implode( '|', $values );
// strip all shortcodes but keep content
// $the_content = preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $the_content);
// strip all shortcodes except $exclude_codes and keep all content
$the_content = preg_replace( "~(?:\[/?)(?!(?:$exclude_codes))[^/\]]+/?\]~s", '', $the_content );
echo $the_content;
you want to remain some shortcodes you can't use strip_shortcodes() for that.
Best solution, solved.
Just add the following code to file wp-includes/rest-api.php, at the bottom:
/**
* Modify REST API content for pages to force
* shortcodes to render since Visual Composer does not
* do this
*/
add_action( 'rest_api_init', function ()
{
register_rest_field(
'page',
'content',
array(
'get_callback' => 'compasshb_do_shortcodes',
'update_callback' => null,
'schema' => null,
)
);
});
function compasshb_do_shortcodes( $object, $field_name, $request )
{
WPBMap::addAllMappedShortcodes(); // This does all the work
global $post;
$post = get_post ($object['id']);
$output['rendered'] = apply_filters( 'the_content', $post->post_content );
return $output;
}
I took it somewhere and update it a bit, to work a bit better :).
in functions.php add this function:
/** Function that cuts post excerpt to the number of a word based on previously set global * variable $word_count, which is defined below */
if(!function_exists('kc_excerpt')) {
function kc_excerpt($excerpt_length = 20) {
global $word_count, $post;
$word_count = $excerpt_length;
$post_excerpt = get_the_excerpt($post) != "" ? get_the_excerpt($post) : strip_tags(do_shortcode(get_the_content($post)));
$clean_excerpt = strpos($post_excerpt, '...') ? strstr($post_excerpt, '...', true) : $post_excerpt;
/** add by PR */
$clean_excerpt = strip_shortcodes(remove_vc_from_excerpt($clean_excerpt));
/** end PR mod */
$excerpt_word_array = explode (' ',$clean_excerpt);
$excerpt_word_array = array_slice ($excerpt_word_array, 0, $word_count);
$excerpt = implode (' ', $excerpt_word_array).'...'; echo ''.$excerpt.'';
}
}
and after that you call it normally kc_excerpt(20); and it will return normal post_content/excerpt
How to remove visual composer from wp post: i.e [vc_row][vc_column width=\"2/3\"][distance][vc_single_image image=\"40530\" img_size=\"large\"][distance][distance][distance][vc_column_text]
Also WP post remvoe short codes and html tags.
while($posts->have_posts()) {
$postContent = get_the_content();
//Remove html tags. and short code
$postContent = strip_tags( do_shortcode( $postContent ) );
//Remove visual composer tags [vc_column] etc
$postContent = preg_replace( "/\[(\/*)?vc_(.*?)\]/", '', $postContent );
}
Looking source code from wordpress api, I did a function to remove some shortcode from content. So this is the result:
function removeShortcode($content, $shortcodeList){
preg_match_all('#\[([^<>&/\[\]\x00-\x20=]++)#', $content, $matches);
$tagnames = array_intersect($shortcodeList, $matches[1]);
if(empty($tagnames)){
return $content;
}
$pattern = get_shortcode_regex($tagnames);
preg_match_all("/$pattern/", $content, $matchesTags);
foreach ($matchesTags[0] as $key => $value) {
$content = str_replace($value, $matchesTags[5][$key], $content);
}
return $content;
}
example:
$content = "<p>Hi, this is a [example]<b>example</b>[/example]. [end]</p>";
$shortcodesToRemove = ["example", "end"];
echo removeShortcode($content, $shortcodesToRemove);
foreach($posts as $po){
$services_array[] = array('id'=>$po->ID,'title'=>$po->post_title, 'description'=>do_shortcode($po->post_content));
}
You should try this.

Sort search results by meta_key value

I really need help with this. Below is a code of my wp page template for search results search.php and everything works just fine. Now, the website is about public events so it's very important that search results are displayed by event date. I've created a custom field called "date" and I'd like to display the results by "date" field value.
I spent a whole week to find a solution but unfortunately I couldn't. Please, help me :)
Here is a code:
<?php
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
if( strlen($query_string) > 0 ) {
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
}
}
$search = new WP_Query($search_query);
?>
<?php if ($search->have_posts()) : while ($search->have_posts() ) : $search->the_post(); ?>
<!-- loop goes here -->
<?php endwhile; else: ?>
<?php endif; ?>
Thank you!!!!
I'd try something else:
In your functions.php or my-plugin.php
add_filter( 'pre_get_posts', 'customize_search_page' );
function customize_search_page($query){
if(!is_admin() && $query->is_search && $query->is_main_query()){
$query->query_vars['meta_key'] = 'your_meta_key';
$query->query_vars['orderby'] = 'meta_value';
$query->query_vars['order'] = 'DESC';
}
return $query;
}
I did not tested it but the pre_get_posts filter will be called before the loop. If it's the right query (search and main) I changed the orderby to an order by meta value.

Getting Next/Previous Post ID using Current Post ID in Wordpress

I want to write a custom next/prev function to dynamically display post information in a fancybox pop-up. So I need to use PHP to get the next and previous Post ID based on whatever Post is currently showing. I know what the current post ID is and I can send that to a function ok, but I can't figure out how to use that ID to obtain the adjacent IDs.
Edit:Here is my code so far (which is not working)
<?php
require_once("../../../wp-blog-header.php");
if (isset($_POST['data'])){
$post_id = $_POST['data'];
}else{
$post_id = "";
}
$wp_query->is_single = true;
$this_post = get_post($post_id);
$in_same_cat = false;
$excluded_categories = '';
$previous = false;
$next_post = get_adjacent_post($in_same_cat,$excluded_categories,$previous);
$post_id = $next_post->id;
$title = $next_post->post_title;
$dataset = array ( "postid"=>$post_id, "posttitle"=>$title );
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode($dataset);
?>
get_adjacent_post() uses the global $post as its reference point, so you'll want to replace this:
$this_post = get_post($post_id);
with this:
global $post;
$post = get_post($post_id);
WordPress also provides get_next_post() and get_previous_post(), which you can use here instead of using get_adjacent_post() with all of those arguments. Here's the final product:
<?php
require_once("../../../wp-blog-header.php");
if (isset($_POST['data'])){
$post_id = $_POST['data'];
}else{
$post_id = "";
}
$wp_query->is_single = true;
global $post;
$post = get_post($post_id);
$previous_post = get_previous_post();
$next_post = get_next_post();
$post_id = $next_post->id;
$title = $next_post->post_title;
$dataset = array ( "postid"=>$post_id, "posttitle"=>$title );
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode($dataset);
?>
I'm not sure what keys you'd like to use for the IDs and titles of the previous and next posts in the $dataset array, so I'll leave that as is for now.
To get this to work I had to change $next_post->id; to $next_post->ID;, i.e. capitalise ID.
I used it in Wordpress on index.php like this – I inserted this at the top of the loop:
<div class="work-post" id="<?php the_ID(); ?>">
then within the loop I use this:
`
if (isset($_POST['data'])){
$post_id = $_POST['data'];
}else{
$post_id = "";
}
$wp_query->is_single = true;
global $post;
$post = get_post($post_id);
$next_post = get_next_post();
$previous_post = get_previous_post();
?>
<!-- call only if a value exists -->
<?php if($next_post) : ?>
<div>PREV.</div>
<?php endif; ?>
<!-- call only if a value exists -->
<!-- call only if a value exists -->
<?php if($previous_post) : ?>
<div>NEXT</div>
<?php endif; ?>
<!-- call only if a value exists -->`
This is my code, it worked good. $post_id is current post ID.
function get_previous_post_id( $post_id ) {
// Get a global post reference since get_adjacent_post() references it
global $post;
// Store the existing post object for later so we don't lose it
$oldGlobal = $post;
// Get the post object for the specified post and place it in the global variable
$post = get_post( $post_id );
// Get the post object for the previous post
$previous_post = get_previous_post();
// Reset our global object
$post = $oldGlobal;
if ( '' == $previous_post )
return 0;
return $previous_post->ID;
}
function get_next_post_id( $post_id ) {
// Get a global post reference since get_adjacent_post() references it
global $post;
// Store the existing post object for later so we don't lose it
$oldGlobal = $post;
// Get the post object for the specified post and place it in the global variable
$post = get_post( $post_id );
// Get the post object for the next post
$next_post = get_next_post();
// Reset our global object
$post = $oldGlobal;
if ( '' == $next_post )
return 0;
return $next_post->ID;
}
Then you just call function. Example:
echo get_previous_post_id( $current_id );
echo get_next_post_id( $current_id );
Good luck!

Categories