Include html href code to shotcode with "show content on a date" - php

I want to use a shortcode to show determinate content depending on a date given, I have this code on function.php on WP:
add_shortcode( 'stime', 'stime_f' );
function stime_f( $atts, $content = '' ) {
$a = shortcode_atts( [
'type' => false,
], $atts );
$output = '';
if ( $a['type'] ) {
$a['type'] = array_map( 'trim', str_getcsv( $a['type'], ',' ) );
}
foreach ($a as $value){
$list0 = $value[0];
$list1 = $value[1];
}
$tm = strtotime($list1);
if ( time() < $tm ) {
$list = "SOON";
return $list;
}
$list = $list0;
return $list;
}
So I used when publish:
[stime type="http://site1.com
http://site2.com,2020-12-05"]
And works, when it's not the date give result: SOON
otherwise result:
http://site1.com
http://site2.com
Results are fine, but I want to use:
[stime type="SITE1
SITE2,2020-12-05"]
I suppose it's for quotes on href and target, there are some way to make it possible?
Thanks

You can use enclosing shortcodes for this.
Below is the updated code:
add_shortcode( 'stime', 'stime_f' );
function stime_f( $atts, $content ) {
if ( $content ) {
$a = array_map( 'trim', str_getcsv( $content, ',' ) );
$list0 = $a[0];
$list1 = $a[1];
$tm = strtotime($list1);
if ( time() < $tm ) {
$list = "SOON";
return $list;
}
$list = $list0;
return $list;
} else {
return '';
}
}
Then use shortcode like this:
[stime] SITE1
SITE2,2020-12-05 [/stime]

Related

Insert Ads after X paragraph php

Hi im try to use a class to insert adsense blocks after x numbers of paragraph etc.
its works with regular text, but dont works with adsense codes.
the full code is HERE
<?php
namespace keesiemeijer\Insert_Content;
function insert_content( $content, $insert_content = '', $args = array() ) {
$args = array_merge( get_defaults(), (array) $args );
if ( empty( $insert_content ) ) {
return $content;
}
// Validate arguments
$args['parent_element_id'] = trim( (string) $args['parent_element_id'] );
$args['insert_element'] = trim( (string) $args['insert_element'] );
$args['insert_element'] = $args['insert_element'] ? $args['insert_element'] : 'p';
$args['insert_after_p'] = abs( intval( $args['insert_after_p'] ) );
$parent_element = false;
// Content wrapped in the parent HTML element (to be inserted).
$insert_content = "<{$args['insert_element']}>{$insert_content}</{$args['insert_element']}>";
$nodes = new \DOMDocument();
// Load the HTML nodes from the content.
#$nodes->loadHTML( $content );
if ( $args['parent_element_id'] ) {
$parent_element = $nodes->getElementById( $args['parent_element_id'] );
if ( !$parent_element ) {
// Parent element not found.
return $content;
}
// Get all paragraphs from the parent element.
$p = $parent_element->getElementsByTagName( 'p' );
} else {
// Get all paragraphs from the content.
$p = $nodes->getElementsByTagName( 'p' );
}
$insert_nodes = new \DOMDocument();
#$insert_nodes->loadHTML( $insert_content );
$insert_element = $insert_nodes->getElementsByTagName( $args['insert_element'] )->item( 0 );
if ( !$insert_element ) {
return $content;
}
// Get paragraph indexes
$nodelist = get_node_indexes( $p, $args );
// Check if paragraphs are found.
if ( !empty( $nodelist ) ) {
$insert_index = get_item_index( $nodelist, $args );
if ( false === $insert_index ) {
return $content;
}
// Insert content after this (paragraph) node.
$insert_node = $p->item( $insert_index );
// Insert the nodes
insert_content_element( $nodes, $insert_node, $insert_element );
$html = get_HTML( $nodes );
if ( $html ) {
$content = $html;
}
} else {
// No paragraphs found.
if ( (bool) $args['insert_if_no_p'] ) {
if ( $parent_element ) {
// Insert content after parent element.
insert_content_element( $nodes, $parent_element, $insert_element );
$html = get_HTML( $nodes );
if ( $html ) {
$content = $html;
}
} else {
// Add insert content after the content/
$content .= $insert_content;
}
}
}
return $content;
}
/**
* Get default arguments.
*
* #return array Array with default arguments.
*/
function get_defaults() {
return array(
'parent_element_id' => '',
'insert_element' => 'p',
'insert_after_p' => '',
'insert_if_no_p' => true,
'top_level_p_only' => true,
);
}
function get_node_indexes( $nodes, $args ) {
$args = array_merge( get_defaults(), (array) $args );
$nodelist = array();
$length = isset( $nodes->length ) ? $nodes->length : 0;
$parent_id = trim( $args['parent_element_id'] );
for ( $i = 0; $i < $length; ++$i ) {
$nodelist[ $i ] = $i;
$parent = false;
$node = $nodes->item( $i );
if ( $parent_id ) {
if ( $node->parentNode->hasAttribute( 'id' ) ) {
$parent_id_attr = $node->parentNode->getAttribute( 'id' );
$parent = ( $parent_id === $parent_id_attr );
}
} else {
$parent = ( 'body' === $node->parentNode->nodeName );
}
if ( (bool) $args['top_level_p_only'] && !$parent ) {
// Remove nested paragraphs from the list.
unset( $nodelist[ $i ] );
}
}
return array_values( $nodelist );
}
function get_item_index( $nodelist, $args ) {
if ( empty( $nodelist ) ) {
return false;
}
$args = array_merge( get_defaults(), (array) $args );
$count = count( $nodelist );
$insert_index = abs( intval( $args['insert_after_p'] ) );
end( $nodelist );
$last = key( $nodelist );
reset( $nodelist );
if ( !$insert_index ) {
if ( 1 < $count ) {
// More than one paragraph found.
// Get middle position to insert the HTML.
$insert_index = $nodelist[ floor( $count / 2 ) -1 ];
} else {
// One paragraph
$insert_index = $last;
}
} else {
// start counting at 0.
--$insert_index;
--$count;
if ( $insert_index > $count ) {
if ( (bool) $args['insert_if_no_p'] ) {
// insert after last paragraph.
$insert_index = $last;
} else {
return false;
}
}
}
return $nodelist[ $insert_index ];
}
/**
* Insert an element (and it's child elements) in the content.
*
* #param object $nodes DOMNodeList instance containing all nodes.
* #param object $insert_node DOMElement object to insert nodes after
* #param object $insert DOMElement object to insert
* #return void
*/
function insert_content_element( $nodes, $insert_node, $insert_element ) {
$next_sibling = isset( $insert_node->nextSibling ) ? $insert_node->nextSibling : false;
if ( $next_sibling ) {
// get sibling element (exluding text nodes and whitespace).
$next_sibling = nextElementSibling( $insert_node );
}
if ( $next_sibling ) {
// Insert before next sibling.
$next_sibling->parentNode->insertBefore( $nodes->importNode( $insert_element, true ), $next_sibling );
} else {
// Insert as child of parent element.
$insert_node->parentNode->appendChild( $nodes->importNode( $insert_element, true ) );
}
}
function nextElementSibling( $node ) {
while ( $node && ( $node = $node->nextSibling ) ) {
if ( $node instanceof \DOMElement ) {
break;
}
}
return $node;
}
function get_HTML( $nodes ) {
$body_node = $nodes->getElementsByTagName( 'body' )->item( 0 );
if ( $body_node ) {
// Convert nodes from the body element to a string containing HTML.
$content = $nodes->saveHTML( $body_node );
// Remove first body element only.
$replace_count = 1;
return str_replace( array( '<body>', '</body>' ) , array( '', '' ), $content, $replace_count );
}
return '';
}
to call the function
$args = array(
'insert_after_p' => 3, // Insert after the second paragraph
);
echo keesiemeijer\Insert_Content\insert_content($content, $insert_content, $args );

Cut a string/url to always get a final string/url with a specific data and it's value in php

I have an url that contain the word "&key".
The "&key" word can be at the beginning or at the end of our url.
Ex1= http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxx&c4=xxx&f1=xxx
Ex2= http://xxxxx.com?c1=xxx&key=xxx&c2=xxx&c3=xxx&c4=xxx&f1=xxx
What I would like to get is all the time the url with the Key element and it's value.
R1: http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxx
R2: http://xxxxx.com?c1=xxx&key=xxx
Here is what I have done:
$lp_sp_ad_publisher = "http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxxc4=xxxf1=xxx";
$lp_sp_ad_publisher_cut_link = explode("&", $lp_sp_ad_publisher_cut[1]); // tab
$lp_sp_ad_publisher_cut_link_final = $lp_sp_ad_publisher_cut_link[0]; // http://xxxxx.com?c1=xxx
$counter = 1;
// finding &key inside $lp_sp_ad_publisher_cut_link_final
while ((strpos($lp_sp_ad_publisher_cut_link_final, '&key')) !== false);
{
$lp_sp_ad_publisher_cut_link_final .= $lp_sp_ad_publisher_cut_link[$counter];
echo 'counter: ' . $counter . ' link: ' . $lp_sp_ad_publisher_cut_link_final . '<br/>';
$counter++;
}
I'm only looping once all the time. I guess the while loop isn't refreshing with the inside new value. Any solution?
EDIT: Sorry, I misunderstood the question.
This is tricky because the url key and value can be anything, so it might be safer to breakdown the URL using a combination of parse_url() and parse_str(), then put the url back together leaving off the part you don't want. Something like this:
function cut_url( $url='', $key='' )
{
$output = '';
$parts = parse_url( $url );
$query = array();
if( isset( $parts['scheme'] ) )
{
$output .= $parts['scheme'].'://';
}
if( isset( $parts['host'] ) )
{
$output .= $parts['host'];
}
if( isset( $parts['path'] ) )
{
$output .= $parts['path'];
}
if( isset( $parts['query'] ) )
{
$output .= '?';
parse_str( $parts['query'], $query );
}
foreach( $query as $qkey => $qvalue )
{
$output .= $qkey.'='.$qvalue.'&';
if( $qkey == $key ) break;
}
return rtrim( $output, '&' );
}
Usage:
$input = 'https://www.xxxxx.com/test/path/index.php?c1=xxx&c2=xxx&key=xxx&c3=xxx&c4=xxx&f1=xxx';
$output = cut_url( $input, 'key' );
Output:
https://www.xxxxx.com/test/path/index.php?c1=xxx&c2=xxx&key=xxx
If the intention is to always ensure that the parameter key and it's associated value appear at the end of the string, how about something like:
$tmp=array();$key='';
$parts=explode( '&', parse_url( $_SERVER['REQUEST_URI'], PHP_URL_QUERY ) );
foreach( $parts as $pair ) {
list( $param,$value )=explode( '=',$pair );
if( $param=='key' )$key=$pair;
else $tmp[]=$pair;
}
$query = implode( '&', array( implode( '&', $tmp ), $key ) );
echo $query;
or,
parse_str( $_SERVER['QUERY_STRING'], $pieces );
foreach( $pieces as $param => $value ){
if( $param=='key' ) $key=$param.'='.$value;
else $tmp[]=$param.'='.$value;
}
$query = implode( '&', array( implode( '&', $tmp ), $key ) );
update
I'm puzzled that you were "not getting the good result"!
consider the url:
https://localhost/index.php?sort=0&dir=false&tax=23&cost=99&aardvark=creepy&key=banana&tree=large&ac=dc&limit=1000#569f945674935
The above would output:
sort=0&dir=false&tax=23&cost=99&aardvark=creepy&tree=large&ac=dc&limit=1000&key=banana
so the key=banana gets placed last using either method above.

Extract shortcode parameters in content - Wordpress

Think about a post content like below:
[shortcode a="a_param"]
... Some content and shortcodes here
[shortcode b="b_param"]
.. Again some content here
[shortcode c="c_param"]
I have a shortcode that takes 3 or more parameters.
I want to find out how many times the shortcode is used at the content and its parameters in an array like,
array (
[0] => array(a => a_param, b=> null, c=>null),
[1] => array(a => null, b=> b_param, c=>null),
[2] => array(a => null, b=> null, c=>c_param),
)
I need to do this in the_content filter, wp_head filter or something similar.
How can I do this ?
Thank you,
In wordpress get_shortcode_regex() function returns regular expression used to search for shortcodes inside posts.
$pattern = get_shortcode_regex();
Then preg_match the pattern with the post content
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
If it return true, then extracted shortcode details are saved in $matches variable.
Try
global $post;
$result = array();
//get shortcode regex pattern wordpress function
$pattern = get_shortcode_regex();
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
{
$keys = array();
$result = array();
foreach( $matches[0] as $key => $value) {
// $matches[3] return the shortcode attribute as string
// replace space with '&' for parse_str() function
$get = str_replace(" ", "&" , $matches[3][$key] );
parse_str($get, $output);
//get all shortcode attribute keys
$keys = array_unique( array_merge( $keys, array_keys($output)) );
$result[] = $output;
}
//var_dump($result);
if( $keys && $result ) {
// Loop the result array and add the missing shortcode attribute key
foreach ($result as $key => $value) {
// Loop the shortcode attribute key
foreach ($keys as $attr_key) {
$result[$key][$attr_key] = isset( $result[$key][$attr_key] ) ? $result[$key][$attr_key] : NULL;
}
//sort the array key
ksort( $result[$key]);
}
}
//display the result
print_r($result);
}
Just to save time, this is the function I made based on #Tamil Selvan C answer :
function get_shortcode_attributes( $shortcode_tag ) {
global $post;
if( has_shortcode( $post->post_content, $shortcode_tag ) ) {
$output = array();
//get shortcode regex pattern wordpress function
$pattern = get_shortcode_regex( [ $shortcode_tag ] );
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
{
$keys = array();
$output = array();
foreach( $matches[0] as $key => $value) {
// $matches[3] return the shortcode attribute as string
// replace space with '&' for parse_str() function
$get = str_replace(" ", "&" , trim( $matches[3][$key] ) );
$get = str_replace('"', '' , $get );
parse_str( $get, $sub_output );
//get all shortcode attribute keys
$keys = array_unique( array_merge( $keys, array_keys( $sub_output )) );
$output[] = $sub_output;
}
if( $keys && $output ) {
// Loop the output array and add the missing shortcode attribute key
foreach ($output as $key => $value) {
// Loop the shortcode attribute key
foreach ($keys as $attr_key) {
$output[$key][$attr_key] = isset( $output[$key] ) && isset( $output[$key] ) ? $output[$key][$attr_key] : NULL;
}
//sort the array key
ksort( $output[$key]);
}
}
}
return $output;
}else{
return false;
}
}

Get Inner HTML - PHP

I have the following code:
$data = file_get_contents('http://www.robotevents.com/robot-competitions/vex-robotics-competition?limit=all');
echo "Downloaded";
$dom = new domDocument;
#$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(2)->getElementsByTagName('tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
for ($i = 0; $i < $cols->length; $i++) {
echo $cols->item($i)->nodeValue . "\n";
}
}
The final field has an Link which I need to store the URL of. Also, The script outputs characters such as "Â". Does anyone know how to do/fix these things?
I would recommend not using DOM to parse HTML, as it has problems with invalid HTML. INstead use regular expression
I use this class:
<?php
/**
* Class to return HTML elements from a HTML document
* #version 0.3.1
*/
class HTMLQuery
{
protected $selfClosingTags = array( 'area', 'base', 'br', 'hr', 'img', 'input', 'link', 'meta', 'param' );
private $html;
function __construct( $html = false )
{
if( $html !== false )
$this->load( $html );
}
/**
* Load a HTML string
*/
public function load( $html )
{
$this->html = $html;
}
/**
* Returns elements from the HTML
*/
public function getElements( $element, $attribute_match = false, $value_match = false )
{
if( in_array( $element, $this->selfClosingTags ) )
preg_match_all( "/<$element *(.*)*\/>/isU", $this->html, $matches );
else
preg_match_all( "/<$element(.*)>(.*)<\/$element>/isU", $this->html, $matches );
if( $matches )
{
#Create an array of matched elements with attributes and content
foreach( $matches[0] as $key => $el )
{
$current_el = array( 'name' => $element );
$attributes = $this->parseAttributes( $matches[1][$key] );
if( $attributes )
$current_el['attributes'] = $attributes;
if( $matches[2][$key] )
$current_el['content'] = $matches[2][$key];
$elements[] = $current_el;
}
#Return only elements with a specific attribute and or value if specified
if( $attribute_match != false && $elements )
{
foreach( $elements as $el_key => $current_el )
{
if( $current_el['attributes'] )
{
foreach( $current_el['attributes'] as $att_name => $att_value )
{
$keep = false;
if( $att_name == $attribute_match )
{
$keep = true;
if( $value_match == false )
break;
}
if( $value_match && ( $att_value == $value_match ) )
{
$keep = true;
break;
}
elseif( $value_match && ( $att_value != $value_match ) )
$keep = false;
}
if( $keep == false )
unset( $elements[$el_key] );
}
else
unset( $elements[$el_key] );
}
}
}
if( $elements )
return array_values( $elements );
else
return array();
}
/**
* Return an associateive array of all the form inputs
*/
public function getFormValues()
{
$inputs = $this->getElements( 'input' );
$textareas = $this->getElements( 'textarea' );
$buttons = $this->getElements( 'button' );
$elements = array_merge( $inputs, $textareas, $buttons );
if( $elements )
{
foreach( $elements as $current_el )
{
$attribute_name = mb_strtolower( $current_el['attributes']['name'] );
if( in_array( $current_el['name'], array( 'input', 'button' ) ) )
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['attributes']['value'] ) )
$form_values[$attribute_name] = $current_el['attributes']['value'];
}
else
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['content'] ) )
$form_values[$attribute_name] = $current_el['content'];
}
}
}
return $form_values;
}
/**
* Parses attributes into an array
*/
private function parseAttributes( $str )
{
$str = trim( rtrim( trim( $str ), '/' ) );
if( $str )
{
preg_match_all( "/([^ =]+)\s*=\s*[\"'“”]{0,1}([^\"'“”]*)[\"'“”]{0,1}/i", $str, $matches );
if( $matches[1] )
{
foreach( $matches[1] as $key => $att )
{
$attribute_name = mb_strtolower( $att );
$attributes[$attribute_name] = $matches[2][$key];
}
}
}
return $attributes;
}
}
?>
Usage is:
$c = new HTMLQuery();
$x = $c->getElements( 'tr' );
print_r( $x );

PHP can not echo each array

I can not echo each Array. Dont know what i am doing wrong. What would be the way to echo each Array? Have tried some ways like below to echo but no success.
function simple_social_sharing( $attr_twitter = null, $attr_items = null ) {
// parse variables
$twitter_account = $attr_twitter;
$item_toggles = $attr_items;
// get post content and urlencode it
global $post;
$browser_title_encoded = urlencode( trim( wp_title( '', false, 'right' ) ) );
$page_title_encoded = urlencode( get_the_title() );
$page_url_encoded = urlencode( get_permalink($post->ID) );
// create share items array
$share_items = array ();
// set each item
$item_facebook = array(
"class" => "facebook",
"href" => "http://www.facebook.com/sharer.php?u={$page_url_encoded}&t={$browser_title_encoded}",
"text" => "Share on Facebook"
);
$item_twitter = array(
"class" => "twitter",
"href" => "http://twitter.com/share?text={$page_title_encoded}&url={$page_url_encoded}&via={$twitter_account}",
"text" => "Share on Twitter"
);
$item_google = array(
"class" => "google",
"href" => "http://plus.google.com/share?url={$page_url_encoded}",
"text" => "Share on Google+"
);
// test whether to display each item
if($item_toggles) {
// explode into array
$item_toggles_array = explode( ",", $item_toggles );
// set each item on or off
$show_facebook = $item_toggles_array['0'];
$show_twitter = $item_toggles_array['1'];
$show_google = $item_toggles_array['2'];
}
else {
$display_all_items = 1;
}
// form array of items set to 1
if( $show_facebook==1 || $display_all_items ) {
array_push( $share_items, $item_facebook );
}
if( $show_twitter==1 || $display_all_items) {
array_push( $share_items, $item_twitter );
}
if( $show_google==1 || $display_all_items) {
array_push( $share_items, $item_google );
}
// if one or more items
if ( ! empty( $share_items ) ) {
// create output
$share_output = "<ul class=\"ss-share\">\n";
foreach ( $share_items as $share_item ) {
$share_output .= "<li class=\"ss-share-item\">\n";
$share_output .= "<a class=\"ss-share-link ico-{$share_item['class']}\" href=\"{$share_item["href"]}\" rel=\"nofollow\" target=\"_blank\">{$share_item['text']}</a>\n";
$share_output .= "</li>\n";
}
$share_output .= "</ul>";
// echo output
echo $share_output;
}
}
// add shortcode to output buttons
function simple_social_sharing_shortcode( $atts, $content = null ) {
// parse variables / set defaults
extract( shortcode_atts( array(
'twitter' => '',
'display' => '1,1,1',
), $atts ) );
// output buttons
ob_start();
simple_social_sharing( $twitter, $display );
$output_string = ob_get_contents();
ob_end_clean();
return force_balance_tags( $output_string );
}
Developers call function is not working too
<?php simple_social_sharing('twitteraccount', '1,1,1'); ?>
I have tried to call each Array by this way but it's wrong.
<?php simple_social_sharing([1]); ?>
Down towards the bottom you have this snippet in your foreach block:
... href=\"{$share_item["href"]}\" ...
The double quotes around href are going to cause you a problem.
You need to have it as
... href=\"{$share_item['href']}\" ...
Function should RETURN values and does not ECHO it..
Instead of echo $share_output;, you should have it return $share_output;
Echo the function's return value (if array, then print_r it else echo it) to see output
<?php echo simple_social_sharing('twitteraccount', '1,1,1'); //NOTE THE 'echo' HERE.. ?>

Categories