Setting WordPress Title into Two Separate Variables - php

I have a custom post type that has a bunch of posts all formatted like so
Artist - Song Title
for example
The Smashing Pumpkins - Quiet
I am trying to put 'Artist' in a variable $artist and 'Song Title' in a variable $song
$artistsong = get_the_title();
$songeach = explode("-", $artistsong);
$artist = $songeach[0];
$song = $songeach[1];
But this does not work. Echo-ing $artist gets the full title
The Smashing Pumpkins - Quiet
and echoing $song does not output anything
This works if I am just starting from plaintext, but not with 'get_the_title()'
$song = "The Smashing Pumpkins - Quiet";
$songeach = explode("-", $song);
$artist = trim($songeach[0]);
$song = trim($songeach[1]);
echo $artist;
//echos 'The Smashing Pumpkins'
echo $song;
//echos 'Quiet'
Is there another way to put the full title into a variable initially other than get_the_title() which does not seem to be working for me, or am I missing something else?

Add this code to your functions.php
function get_the_title_keep_hyphen( $post = 0 ) {
$post = get_post( $post );
$title = isset( $post->post_title ) ? $post->post_title : '';
$id = isset( $post->ID ) ? $post->ID : 0;
if ( ! is_admin() ) {
if ( ! empty( $post->post_password ) ) {
/**
* Filter the text prepended to the post title for protected posts.
*
* The filter is only applied on the front end.
*
* #since 2.8.0
*
* #param string $prepend Text displayed before the post title.
* Default 'Protected: %s'.
* #param WP_Post $post Current post object.
*/
$protected_title_format = apply_filters( 'protected_title_format', __( 'Protected: %s' ), $post );
$title = sprintf( $protected_title_format, $title );
} elseif ( isset( $post->post_status ) && 'private' == $post->post_status ) {
/**
* Filter the text prepended to the post title of private posts.
*
* The filter is only applied on the front end.
*
* #since 2.8.0
*
* #param string $prepend Text displayed before the post title.
* Default 'Private: %s'.
* #param WP_Post $post Current post object.
*/
$private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ), $post );
$title = sprintf( $private_title_format, $title );
}
}
/**
* Filter the post title.
*
* #since 0.71
*
* #param string $title The post title.
* #param int $id The post ID.
*/
return $title;
}
And use this code in your single.php
$artistsong = get_the_title_keep_hyphen();
$songeach = explode(" - ", $artistsong);
$artist = $songeach[0];
$song = $songeach[1];
See the last line
I change from return apply_filters( 'the_title', $title, $id ); to return $title;
Because apply_filters function change the hyphen from - => –.

It's because of the dash symbol.
Try $songeach = explode("P", $artistsong); and you'll see what I mean. You could try a different character between artist and song title - although probably not ideal.

Related

Post title is duplicating if have_posts

I am trying to add some post titles from a custom post category. I currently have it printing the correct amount of <li> but unfortunately it is the same name. You will see I narrow it down using meta, so I am getting 5 results all the same name.
I do not pretend to be a pro at this, so I am humbly asking for any help that the community may have.
Thanks In advance.
I have tried doing a foreach and also doing the if have_posts. both have yielded the same result.
$page_title = get_the_title();
$args = array(
'orderby' => 'title',
'post_type' => 'person',
'post_status' => 'publish',
'meta_key' => 'division',
'meta_value' => 'Singles'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ):
$string .= '<ul>';
while( $query->have_posts() ):
$query->the_post();
$string .= '<li>' . get_the_title() . '</li>';
endwhile;
$string .= '</ul>';
echo $string;
wp_reset_postdata();
else :
// No, we don't have any posts, so maybe we display a nice message
echo "<p class='no-posts'>" . __( "Sorry, there are no posts at this time." ) . "</p>";
endif;
So what we are going for is looking for how many posts exist in "Singles" (in my case that is 5) and printing the post title for each one in an <li>. Currently it prints 1 of the 5, 5 times.
get_the_title() has the following implementation
function get_the_title( $post = 0 ) {
$post = get_post( $post );
$title = isset( $post->post_title ) ? $post->post_title : '';
$id = isset( $post->ID ) ? $post->ID : 0;
if ( ! is_admin() ) {
if ( ! empty( $post->post_password ) ) {
/**
* Filters the text prepended to the post title for protected posts.
*
* The filter is only applied on the front end.
*
* #since 2.8.0
*
* #param string $prepend Text displayed before the post title.
* Default 'Protected: %s'.
* #param WP_Post $post Current post object.
*/
$protected_title_format = apply_filters( 'protected_title_format', __( 'Protected: %s' ), $post );
$title = sprintf( $protected_title_format, $title );
} elseif ( isset( $post->post_status ) && 'private' == $post->post_status ) {
/**
* Filters the text prepended to the post title of private posts.
*
* The filter is only applied on the front end.
*
* #since 2.8.0
*
* #param string $prepend Text displayed before the post title.
* Default 'Private: %s'.
* #param WP_Post $post Current post object.
*/
$private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ), $post );
$title = sprintf( $private_title_format, $title );
}
}
/**
* Filters the post title.
*
* #since 0.71
*
* #param string $title The post title.
* #param int $id The post ID.
*/
return apply_filters( 'the_title', $title, $id );
}
As you can see you can pass a post to it and then it will get its title. Since you didn't pass a post to it, it didn't get a title for you. Suggestion:
$page_title = get_the_title();
$args = array(
'orderby' => 'title',
'post_type' => 'person',
'post_status' => 'publish',
'meta_key' => 'division',
'meta_value' => 'Singles'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ):
$string .= '<ul>';
while( $query->have_posts() ):
$string .= '<li>' . get_the_title($query->the_post()) . '</li>';
endwhile;
$string .= '</ul>';
echo $string;
wp_reset_postdata();
else :
// No, we don't have any posts, so maybe we display a nice message
echo "<p class='no-posts'>" . __( "Sorry, there are no posts at this time." ) . "</p>";
endif;

Add Genesis author box content wrapper

I need to add a wrapper div around all the content within the author box.
What filter code do I need to change the genesis_author_box into this:
<section class="author-box" itemprop="author" itemscope="" itemtype="https://schema.org/Person">
<div class="author-box-wrap">
<img alt="" src="" srcset="" class="avatar avatar-150 photo" height="150" width="150">
<h4 class="author-box-title">About <span itemprop="name">Author Name</span></h4>
<div class="author-box-content" itemprop="description">Description Text</div>
</div>
</section>
Here is the default Genesis markup:
<section class="author-box" itemprop="author" itemscope="" itemtype="https://schema.org/Person">
<img alt="" src="" srcset="" class="avatar avatar-150 photo" height="150" width="150">
<h4 class="author-box-title">About <span itemprop="name">Author Name</span></h4>
<div class="author-box-content" itemprop="description">Description Text</div>
</section>
Here is the code that assembles the default Genesis markup:
/**
* Echo the the author box and its contents.
*
* The title is filterable via `genesis_author_box_title`, and the gravatar size is filterable via
* `genesis_author_box_gravatar_size`.
*
* The final output is filterable via `genesis_author_box`, which passes many variables through.
*
* #since 1.3.0
*
* #global WP_User $authordata Author (user) object.
*
* #param string $context Optional. Allows different author box markup for different contexts, specifically 'single'.
* Default is empty string.
* #param bool $echo Optional. If true, the author box will echo. If false, it will be returned.
* #return string HTML for author box if `$echo` param is falsy.
*/
function genesis_author_box( $context = '', $echo = true ) {
global $authordata;
$authordata = is_object( $authordata ) ? $authordata : get_userdata( get_query_var( 'author' ) );
$gravatar_size = apply_filters( 'genesis_author_box_gravatar_size', 70, $context );
$gravatar = get_avatar( get_the_author_meta( 'email' ), $gravatar_size );
$description = wpautop( get_the_author_meta( 'description' ) );
// The author box markup, contextual.
if ( genesis_html5() ) {
$title = __( 'About', 'genesis' ) . ' <span itemprop="name">' . get_the_author() . '</span>';
/**
* Author box title filter.
*
* Allows you to filter the title of the author box. $context passed as second parameter to allow for contextual filtering.
*
* #since unknown
*
* #param string $title Assembled Title.
* #param string $context Context.
*/
$title = apply_filters( 'genesis_author_box_title', $title, $context );
$heading_element = 'h1';
if ( 'single' === $context && ! genesis_get_seo_option( 'semantic_headings' ) ) {
$heading_element = 'h4';
} elseif ( genesis_a11y( 'headings' ) || get_the_author_meta( 'headline', (int) get_query_var( 'author' ) ) ) {
$heading_element = 'h4';
}
$pattern = sprintf( '<section %s>', genesis_attr( 'author-box' ) );
$pattern .= '%s<' . $heading_element . ' class="author-box-title">%s</' . $heading_element . '>';
$pattern .= '<div class="author-box-content" itemprop="description">%s</div>';
$pattern .= '</section>';
} else {
$title = apply_filters( 'genesis_author_box_title', sprintf( '<strong>%s %s</strong>', __( 'About', 'genesis' ), get_the_author() ), $context );
$pattern = '<div class="author-box">%s<h1>%s</h1><div>%s</div></div>';
if ( 'single' === $context || get_the_author_meta( 'headline', (int) get_query_var( 'author' ) ) ) {
$pattern = '<div class="author-box"><div>%s %s<br />%s</div></div>';
}
}
$output = sprintf( $pattern, $gravatar, $title, $description );
/**
* Author box output filter.
*
* Allows you to filter the full output of the author box.
*
* #since unknown
*
* #param string $output Assembled output.
* #param string $context Context.
* #param string $pattern (s)printf pattern.
* #param string $context Gravatar.
* #param string $context Title.
* #param string $context Description.
*/
$output = apply_filters( 'genesis_author_box', $output, $context, $pattern, $gravatar, $title, $description );
if ( $echo ) {
echo $output;
return null;
} else {
return $output;
}
My PHP is really rough... Thank you for your help!
Give this a try:
add_filter( 'genesis_author_box', 'my_filter_author_box', 10, 3 );
function my_filter_author_box( $output, $context ) {
$output = preg_replace( '/<section (.+?)>(.+)<\/section>/ms', '<section $1><div class="author-box-wrap">$2</div></section>', $output );
return $output;
}
It may be worth reconsidering why you need to add the inner wrapping div and see if you can work out a better way to style it instead.

Wordpress shortcode display as text

I have problem with WP shortcodes.
When I am trying to publish a short code it is displayed as text.
Ii looks like this:
enter image description here
I did try:
Shortcode rendering as text not as shortcode should
and may others.
This is my shortcode.php
<?php
/**
* WordPress API for creating bbcode like tags or what WordPress calls
* "shortcodes." The tag and attribute parsing or regular expression code is
* based on the Textpattern tag parser.
*
* A few examples are below:
*
* [shortcode /]
* [shortcode foo="bar" baz="bing" /]
* [shortcode foo="bar"]content[/shortcode]
*
* Shortcode tags support attributes and enclosed content, but does not entirely
* support inline shortcodes in other shortcodes. You will have to call the
* shortcode parser in your function to account for that.
*
* {#internal
* Please be aware that the above note was made during the beta of WordPress 2.6
* and in the future may not be accurate. Please update the note when it is no
* longer the case.}}
*
* To apply shortcode tags to content:
*
* $out = do_shortcode( $content );
*
* #link https://codex.wordpress.org/Shortcode_API
*
* #package WordPress
* #subpackage Shortcodes
* #since 2.5.0
*/
/**
* Container for storing shortcode tags and their hook to call for the shortcode
*
* #since 2.5.0
*
* #name $shortcode_tags
* #var array
* #global array $shortcode_tags
*/
$shortcode_tags = array();
/**
* Add hook for shortcode tag.
*
* There can only be one hook for each shortcode. Which means that if another
* plugin has a similar shortcode, it will override yours or yours will override
* theirs depending on which order the plugins are included and/or ran.
*
* Simplest example of a shortcode tag using the API:
*
* // [footag foo="bar"]
* function footag_func( $atts ) {
* return "foo = {
* $atts[foo]
* }";
* }
* add_shortcode( 'footag', 'footag_func' );
*
* Example with nice attribute defaults:
*
* // [bartag foo="bar"]
* function bartag_func( $atts ) {
* $args = shortcode_atts( array(
* 'foo' => 'no foo',
* 'baz' => 'default baz',
* ), $atts );
*
* return "foo = {$args['foo']}";
* }
* add_shortcode( 'bartag', 'bartag_func' );
*
* Example with enclosed content:
*
* // [baztag]content[/baztag]
* function baztag_func( $atts, $content = '' ) {
* return "content = $content";
* }
* add_shortcode( 'baztag', 'baztag_func' );
*
* #since 2.5.0
*
* #global array $shortcode_tags
*
* #param string $tag Shortcode tag to be searched in post content.
* #param callable $func Hook to run when shortcode is found.
*/
function add_shortcode($tag, $func) {
global $shortcode_tags;
if ( '' == trim( $tag ) ) {
$message = __( 'Invalid shortcode name: Empty name given.' );
_doing_it_wrong( __FUNCTION__, $message, '4.4.0' );
return;
}
if ( 0 !== preg_match( '#[<>&/\[\]\x00-\x20=]#', $tag ) ) {
/* translators: 1: shortcode name, 2: space separated list of reserved characters */
$message = sprintf( __( 'Invalid shortcode name: %1$s. Do not use spaces or reserved characters: %2$s' ), $tag, '& / < > [ ] =' );
_doing_it_wrong( __FUNCTION__, $message, '4.4.0' );
return;
}
$shortcode_tags[ $tag ] = $func;
}
/**
* Removes hook for shortcode.
*
* #since 2.5.0
*
* #global array $shortcode_tags
*
* #param string $tag Shortcode tag to remove hook for.
*/
function remove_shortcode($tag) {
global $shortcode_tags;
unset($shortcode_tags[$tag]);
}
/**
* Clear all shortcodes.
*
* This function is simple, it clears all of the shortcode tags by replacing the
* shortcodes global by a empty array. This is actually a very efficient method
* for removing all shortcodes.
*
* #since 2.5.0
*
* #global array $shortcode_tags
*/
/*function remove_all_shortcodes() {
global $shortcode_tags;
$shortcode_tags = array();
}
*/
/**
* Whether a registered shortcode exists named $tag
*
* #since 3.6.0
*
* #global array $shortcode_tags List of shortcode tags and their callback hooks.
*
* #param string $tag Shortcode tag to check.
* #return bool Whether the given shortcode exists.
*/
function shortcode_exists( $tag ) {
global $shortcode_tags;
return array_key_exists( $tag, $shortcode_tags );
}
/**
* Whether the passed content contains the specified shortcode
*
* #since 3.6.0
*
* #global array $shortcode_tags
*
* #param string $content Content to search for shortcodes.
* #param string $tag Shortcode tag to check.
* #return bool Whether the passed content contains the given shortcode.
*/
function has_shortcode( $content, $tag ) {
if ( false === strpos( $content, '[' ) ) {
return false;
}
if ( shortcode_exists( $tag ) ) {
preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );
if ( empty( $matches ) )
return false;
foreach ( $matches as $shortcode ) {
if ( $tag === $shortcode[2] ) {
return true;
} elseif ( ! empty( $shortcode[5] ) && has_shortcode( $shortcode[5], $tag ) ) {
return true;
}
}
}
return false;
}
/**
* Search content for shortcodes and filter shortcodes through their hooks.
*
* If there are no shortcode tags defined, then the content will be returned
* without any filtering. This might cause issues when plugins are disabled but
* the shortcode will still show up in the post or content.
*
* #since 2.5.0
*
* #global array $shortcode_tags List of shortcode tags and their callback hooks.
*
* #param string $content Content to search for shortcodes.
* #param bool $ignore_html When true, shortcodes inside HTML elements will be skipped.
* #return string Content with shortcodes filtered out.
*/
function do_shortcode( $content, $ignore_html = false ) {
global $shortcode_tags;
if ( false === strpos( $content, '[' ) ) {
return $content;
}
if (empty($shortcode_tags) || !is_array($shortcode_tags))
return $content;
// Find all registered tag names in $content.
preg_match_all( '#\[([^<>&/\[\]\x00-\x20=]++)#', $content, $matches );
$tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
if ( empty( $tagnames ) ) {
return $content;
}
$content = do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames );
$pattern = get_shortcode_regex( $tagnames );
$content = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $content );
// Always restore square braces so we don't break things like <!--[if IE ]>
$content = unescape_invalid_shortcodes( $content );
// Making your custom string parses shortcode
$string = do_shortcode( $string );
// If your string has a custom filter, add its tag name in an applicable add_filter function
add_filter( 'my_string_filter_hook_tag_name', 'do_shortcode' );
return $content;
}
/**
* Retrieve the shortcode regular expression for searching.
*
* The regular expression combines the shortcode tags in the regular expression
* in a regex class.
*
* The regular expression contains 6 different sub matches to help with parsing.
*
* 1 - An extra [ to allow for escaping shortcodes with double [[]]
* 2 - The shortcode name
* 3 - The shortcode argument list
* 4 - The self closing /
* 5 - The content of a shortcode when it wraps some content.
* 6 - An extra ] to allow for escaping shortcodes with double [[]]
*
* #since 2.5.0
*
* #global array $shortcode_tags
*
* #param array $tagnames List of shortcodes to find. Optional. Defaults to all registered shortcodes.
* #return string The shortcode search regular expression
*/
function get_shortcode_regex( $tagnames = null ) {
global $shortcode_tags;
if ( empty( $tagnames ) ) {
$tagnames = array_keys( $shortcode_tags );
}
$tagregexp = join( '|', array_map('preg_quote', $tagnames) );
// WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag()
// Also, see shortcode_unautop() and shortcode.js.
return
'\\[' // Opening bracket
. '(\\[?)' // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
. "($tagregexp)" // 2: Shortcode name
. '(?![\\w-])' // Not followed by word character or hyphen
. '(' // 3: Unroll the loop: Inside the opening shortcode tag
. '[^\\]\\/]*' // Not a closing bracket or forward slash
. '(?:'
. '\\/(?!\\])' // A forward slash not followed by a closing bracket
. '[^\\]\\/]*' // Not a closing bracket or forward slash
. ')*?'
. ')'
. '(?:'
. '(\\/)' // 4: Self closing tag ...
. '\\]' // ... and closing bracket
. '|'
. '\\]' // Closing bracket
. '(?:'
. '(' // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
. '[^\\[]*+' // Not an opening bracket
. '(?:'
. '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
. '[^\\[]*+' // Not an opening bracket
. ')*+'
. ')'
. '\\[\\/\\2\\]' // Closing shortcode tag
. ')?'
. ')'
. '(\\]?)'; // 6: Optional second closing brocket for escaping shortcodes: [[tag]]
}
/**
* Regular Expression callable for do_shortcode() for calling shortcode hook.
* #see get_shortcode_regex for details of the match array contents.
*
* #since 2.5.0
* #access private
*
* #global array $shortcode_tags
*
* #param array $m Regular expression match array
* #return string|false False on failure.
*/
function do_shortcode_tag( $m ) {
global $shortcode_tags;
// allow [[foo]] syntax for escaping a tag
if ( $m[1] == '[' && $m[6] == ']' ) {
return substr($m[0], 1, -1);
}
$tag = $m[2];
$attr = shortcode_parse_atts( $m[3] );
if ( ! is_callable( $shortcode_tags[ $tag ] ) ) {
/* translators: %s: shortcode tag */
$message = sprintf( __( 'Attempting to parse a shortcode without a valid callback: %s' ), $tag );
_doing_it_wrong( __FUNCTION__, $message, '4.3.0' );
return $m[0];
}
if ( isset( $m[5] ) ) {
// enclosing tag - extra parameter
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, $m[5], $tag ) . $m[6];
} else {
// self-closing tag
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, null, $tag ) . $m[6];
}
}
/**
* Search only inside HTML elements for shortcodes and process them.
*
* Any [ or ] characters remaining inside elements will be HTML encoded
* to prevent interference with shortcodes that are outside the elements.
* Assumes $content processed by KSES already. Users with unfiltered_html
* capability may get unexpected output if angle braces are nested in tags.
*
* #since 4.2.3
*
* #param string $content Content to search for shortcodes
* #param bool $ignore_html When true, all square braces inside elements will be encoded.
* #param array $tagnames List of shortcodes to find.
* #return string Content with shortcodes filtered out.
*/
function do_shortcodes_in_html_tags( $content, $ignore_html, $tagnames ) {
// Normalize entities in unfiltered HTML before adding placeholders.
$trans = array( '[' => '[', ']' => ']' );
$content = strtr( $content, $trans );
$trans = array( '[' => '[', ']' => ']' );
$pattern = get_shortcode_regex( $tagnames );
$textarr = wp_html_split( $content );
foreach ( $textarr as &$element ) {
if ( '' == $element || '<' !== $element[0] ) {
continue;
}
$noopen = false === strpos( $element, '[' );
$noclose = false === strpos( $element, ']' );
if ( $noopen || $noclose ) {
// This element does not contain shortcodes.
if ( $noopen xor $noclose ) {
// Need to encode stray [ or ] chars.
$element = strtr( $element, $trans );
}
continue;
}
if ( $ignore_html || '<!--' === substr( $element, 0, 4 ) || '<![CDATA[' === substr( $element, 0, 9 ) ) {
// Encode all [ and ] chars.
$element = strtr( $element, $trans );
continue;
}
$attributes = wp_kses_attr_parse( $element );
if ( false === $attributes ) {
// Some plugins are doing things like [name] <[email]>.
if ( 1 === preg_match( '%^<\s*\[\[?[^\[\]]+\]%', $element ) ) {
$element = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $element );
}
// Looks like we found some crazy unfiltered HTML. Skipping it for sanity.
$element = strtr( $element, $trans );
continue;
}
// Get element name
$front = array_shift( $attributes );
$back = array_pop( $attributes );
$matches = array();
preg_match('%[a-zA-Z0-9]+%', $front, $matches);
$elname = $matches[0];
// Look for shortcodes in each attribute separately.
foreach ( $attributes as &$attr ) {
$open = strpos( $attr, '[' );
$close = strpos( $attr, ']' );
if ( false === $open || false === $close ) {
continue; // Go to next attribute. Square braces will be escaped at end of loop.
}
$double = strpos( $attr, '"' );
$single = strpos( $attr, "'" );
if ( ( false === $single || $open < $single ) && ( false === $double || $open < $double ) ) {
// $attr like '[shortcode]' or 'name = [shortcode]' implies unfiltered_html.
// In this specific situation we assume KSES did not run because the input
// was written by an administrator, so we should avoid changing the output
// and we do not need to run KSES here.
$attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr );
} else {
// $attr like 'name = "[shortcode]"' or "name = '[shortcode]'"
// We do not know if $content was unfiltered. Assume KSES ran before shortcodes.
$count = 0;
$new_attr = preg_replace_callback( "/$pattern/", 'do_shortcode_tag', $attr, -1, $count );
if ( $count > 0 ) {
// Sanitize the shortcode output using KSES.
$new_attr = wp_kses_one_attr( $new_attr, $elname );
if ( '' !== trim( $new_attr ) ) {
// The shortcode is safe to use now.
$attr = $new_attr;
}
}
}
}
$element = $front . implode( '', $attributes ) . $back;
// Now encode any remaining [ or ] chars.
$element = strtr( $element, $trans );
}
$content = implode( '', $textarr );
return $content;
}
/**
* Remove placeholders added by do_shortcodes_in_html_tags().
*
* #since 4.2.3
*
* #param string $content Content to search for placeholders.
* #return string Content with placeholders removed.
*/
function unescape_invalid_shortcodes( $content ) {
// Clean up entire string, avoids re-parsing HTML.
$trans = array( '[' => '[', ']' => ']' );
$content = strtr( $content, $trans );
return $content;
}
/**
* Retrieve the shortcode attributes regex.
*
* #since 4.4.0
*
* #return string The shortcode attribute regular expression
*/
function get_shortcode_atts_regex() {
return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
}
/**
* Retrieve all attributes from the shortcodes tag.
*
* The attributes list has the attribute name as the key and the value of the
* attribute as the value in the key/value pair. This allows for easier
* retrieval of the attributes, since all attributes have to be known.
*
* #since 2.5.0
*
* #param string $text
* #return array|string List of attribute values.
* Returns empty array if trim( $text ) == '""'.
* Returns empty string if trim( $text ) == ''.
* All other matches are checked for not empty().
*/
function shortcode_parse_atts($text) {
$atts = array();
$pattern = get_shortcode_atts_regex();
$text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) {
foreach ($match as $m) {
if (!empty($m[1]))
$atts[strtolower($m[1])] = stripcslashes($m[2]);
elseif (!empty($m[3]))
$atts[strtolower($m[3])] = stripcslashes($m[4]);
elseif (!empty($m[5]))
$atts[strtolower($m[5])] = stripcslashes($m[6]);
elseif (isset($m[7]) && strlen($m[7]))
$atts[] = stripcslashes($m[7]);
elseif (isset($m[8]))
$atts[] = stripcslashes($m[8]);
}
// Reject any unclosed HTML elements
foreach( $atts as &$value ) {
if ( false !== strpos( $value, '<' ) ) {
if ( 1 !== preg_match( '/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value ) ) {
$value = '';
}
}
}
} else {
$atts = ltrim($text);
}
return $atts;
}
/**
* Combine user attributes with known attributes and fill in defaults when needed.
*
* The pairs should be considered to be all of the attributes which are
* supported by the caller and given as a list. The returned attributes will
* only contain the attributes in the $pairs list.
*
* If the $atts list has unsupported attributes, then they will be ignored and
* removed from the final returned list.
*
* #since 2.5.0
*
* #param array $pairs Entire list of supported attributes and their defaults.
* #param array $atts User defined attributes in shortcode tag.
* #param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering
* #return array Combined and filtered attribute list.
*/
function shortcode_atts( $pairs, $atts, $shortcode = '' ) {
$atts = (array)$atts;
$out = array();
foreach ($pairs as $name => $default) {
if ( array_key_exists($name, $atts) )
$out[$name] = $atts[$name];
else
$out[$name] = $default;
}
/**
* Filter a shortcode's default attributes.
*
* If the third parameter of the shortcode_atts() function is present then this filter is available.
* The third parameter, $shortcode, is the name of the shortcode.
*
* #since 3.6.0
* #since 4.4.0 Added the `$shortcode` parameter.
*
* #param array $out The output array of shortcode attributes.
* #param array $pairs The supported attributes and their defaults.
* #param array $atts The user defined shortcode attributes.
* #param string $shortcode The shortcode name.
*/
if ( $shortcode ) {
$out = apply_filters( "shortcode_atts_{$shortcode}", $out, $pairs, $atts, $shortcode );
}
return $out;
}
/**
* Remove all shortcode tags from the given content.
*
* #since 2.5.0
*
* #global array $shortcode_tags
*
* #param string $content Content to remove shortcode tags.
* #return string Content without shortcode tags.
*/
function strip_shortcodes( $content ) {
global $shortcode_tags;
if ( false === strpos( $content, '[' ) ) {
return $content;
}
if (empty($shortcode_tags) || !is_array($shortcode_tags))
return $content;
// Find all registered tag names in $content.
preg_match_all( '#\[([^<>&/\[\]\x00-\x20=]++)#', $content, $matches );
$tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
if ( empty( $tagnames ) ) {
return $content;
}
$content = do_shortcodes_in_html_tags( $content, true, $tagnames );
$pattern = get_shortcode_regex( $tagnames );
$content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content );
// Always restore square braces so we don't break things like <!--[if IE ]>
$content = unescape_invalid_shortcodes( $content );
return $content;
}
/**
* Strips a shortcode tag based on RegEx matches against post content.
*
* #since 3.3.0
*
* #param array $m RegEx matches against post content.
* #return string|false The content stripped of the tag, otherwise false.
*/
function strip_shortcode_tag( $m ) {
// allow [[foo]] syntax for escaping a tag
if ( $m[1] == '[' && $m[6] == ']' ) {
return substr($m[0], 1, -1);
}
return $m[1] . $m[6];
}
Please help...
I wanna help but I really dont understand your question.
try change define('WP_DEBUG', true); and see where the problem is.
add_shortcode('check', 'check_scode');
function check_scode($atts){
return '<h1>its working</h1>';
}
add above script test to the bottom of your functions.php in wp-content/themes/your-themes
and put this shortcode
[check]
or with php code, check if your shortcode registered,
if ( ! function_exists( 'check_shortcode' ) ) :
function check_shortcode( $code = '' ) {
global $shortcode_tags;
if ( $code && array_key_exists( $code, $shortcode_tags ) ){
return true;
}
}
endif;
put in the bottom of your functions.php and add this script somewhere,
<?php
if(check_shortcode('gallery_bank')) {
echo '<h1>Shortcode found</h1>';
}else{
echo '<h1>Shortcode <b>not Registered<b></h1>';
}
?>
you should check your theme, search theme check in plugin-install page

blog excerpt in wordpress

I've purchased a theme and the blog excerpt works fine on their demo site, but not on my website's blog overview page.
this is the code I found, but this is the wordpress post-template.php
The theme does not have any blog settings which leads me to think it's a wordpress issues?
Hopre someone can help,
Many thanks!
P.S. Php newbie so please explain how I can fix this.
function get_the_excerpt( $deprecated = '' ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '2.3' );
$post = get_post();
if ( empty( $post ) ) {
return '';
}
if ( post_password_required() ) {
return __( 'There is no excerpt because this is a protected post.' );
}
/**
* Filter the retrieved post excerpt.
*
* #since 1.2.0
*
* #param string $post_excerpt The post excerpt.
*/
return apply_filters( 'get_the_excerpt', $post->post_excerpt );
}
/**
* Whether post has excerpt.
*
* #since 2.3.0
*
* #param int|WP_Post $id Optional. Post ID or post object.
* #return bool
*/
function has_excerpt( $id = 0 ) {
$post = get_post( $id );
return ( !empty( $post->post_excerpt ) );
}
/**
* Display the classes for the post div.
*
* #since 2.7.0
*
* #param string|array $class One or more classes to add to the class list.
* #param int|WP_Post $post_id Optional. Post ID or post object.
*/
function post_class( $class = '', $post_id = null ) {
// Separates classes with a single space, collates classes for post DIV
echo 'class="' . join( ' ', get_post_class( $class, $post_id ) ) . '"';
}
By default the_excerpt() return the text in the excerpt field. Though you can use a filter to change what it returns:
add_filter( 'get_the_excerpt', 'my_custom_excerpt' );
It will trigger this function when the_excerpt() will be called:
function my_custom_excerpt($excerpt) {
if(empty($excerpt)) {
return get_custom_excerpt();
} else {
return $excerpt;
}
}
That way a custom excerpt will be used if the excerpt field is empty. Here is the code for get_custom_excerpt (it will do a "smart" ceasure):
function print_excerpt($length)
{
global $post;
$text = $post->post_excerpt;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
}
$text = strip_shortcodes($text);
$text = strip_tags($text, '<a>'); // change this to the tags you want to keep
if (preg_match('/^.{1,'.$length.'}\b/s', $text, $match))
$text = $match[0];
$excerpt = reverse_strrchr($text, array('.','!'), 1, 100);
if($excerpt) {
echo apply_filters('the_excerpt',$excerpt);
} else {
echo apply_filters('the_excerpt',$text.'...');
}
}
function reverse_strrchr($haystack, $needle, $trail, $offset=0)
{
return strrposa($haystack, $needle, $offset) ? substr($haystack, 0, strrposa($haystack, $needle, $offset) + $trail) : false;
}
// strrpos in Array mode
function strrposa($haystack, $needles=array(), $offset=0)
{
if(!is_array($needles))
$needles = array($needles);
foreach($needles as $query) {
if(strrpos($haystack, $query, $offset) !== false)
return strrpos($haystack, $query, $offset);
}
return false;
}

How to display recent global post in wordpress multisite

I run a wordpress multisite on ayp.no and I am trying to figure out a way to present all subsites with logos and recent posts from all blogs, I know there is a wpmudev premium plugin for this, but I was hoping there was some coding i could do myself (well, obviously not myself, but at least ask here and see)..
First, we need a function to get all sites, with that at hand we iterate thought the array of sites and pull the information with wp_get_recent_posts() (which is a customized version of get_posts()).
Use the following as a Must Use plugin, so the function b5f_print_recent_posts() is available throughout the network:
<?php
/**
* Plugin Name: Recent Network Posts
* Plugin URI: http://stackoverflow.com/q/23713801/1287812
* Description: Creates a function that lists recent posts from all sites of the network. Call it in another plugins or themes.
* Author: brasofilo
*/
/**
* Iterates throught all sites of the network and grab the recent posts
*/
function b5f_print_recent_posts()
{
$blogs = b5f_get_blog_list( 0, 'all', true );
$current_blog_id = get_current_blog_id();
foreach( $blogs as $blog )
{
switch_to_blog( $blog[ 'blog_id' ] );
echo '<h3>' . $blog['name'] . ' - ' . $blog['domain'] . ' - ' . $blog['desc'] . '</h3>';
$posts = wp_get_recent_posts( array(), OBJECT );
if( $posts )
{
foreach( $posts as $post )
{
printf(
'- %s<br />',
get_permalink( $post->ID ),
$post->post_title
);
}
}
}
switch_to_blog( $current_blog_id );
}
/**
* Returns an array of arrays containing information about each public blog
* hosted on this WPMU install.
*
* Only blogs marked as public and flagged as safe (mature flag off) are returned.
*
* #author Frank Bueltge
*
* #param Integer The first blog to return in the array.
* #param Integer The number of blogs to return in the array (thus the size of the array).
* Setting this to string 'all' returns all blogs from $start
* #param Boolean Get also Postcount for each blog, default is False for a better performance
* #param Integer Time until expiration in seconds, default 86400s (1day)
* #return Array Returns an array of arrays each representing a blog.
* Details are represented in the following format:
* blog_id (integer) ID of blog detailed.
* domain (string) Domain used to access this blog.
* path (string) Path used to access this blog.
* postcount (integer) The number of posts in this blog.
* name (string) Blog name.
* desc (string) Blog description.
*/
function b5f_get_blog_list( $start = 0, $num = 10, $details = FALSE, $expires = 86400 ) {
// get blog list from cache
$blogs = get_site_transient( 'multisite_blog_list' );
// For debugging purpose
if ( defined( 'WP_DEBUG' ) && WP_DEBUG )
$blogs = FALSE;
if ( FALSE === $blogs ) {
global $wpdb;
// add limit for select
if ( 'all' === $num )
$limit = '';
else
$limit = "LIMIT $start, $num";
$blogs = $wpdb->get_results(
$wpdb->prepare( "
SELECT blog_id, domain, path
FROM $wpdb->blogs
WHERE site_id = %d
AND public = '1'
AND archived = '0'
AND mature = '0'
AND spam = '0'
AND deleted = '0'
ORDER BY registered ASC
$limit
", $wpdb->siteid ),
ARRAY_A );
// Set the Transient cache
set_site_transient( 'multisite_blog_list', $blogs, $expires );
}
// only if usable, set via var
if ( TRUE === $details ) {
$blog_list = get_site_transient( 'multisite_blog_list_details' );
// For debugging purpose
if ( defined( 'WP_DEBUG' ) && WP_DEBUG )
$blog_list = FALSE;
if ( FALSE === $blog_list ) {
global $wpdb;
$current_blog_id = get_current_blog_id();
foreach ( (array) $blogs as $details ) {
$blog_list[ $details['blog_id'] ] = $details;
$blog_list[ $details['blog_id'] ]['postcount'] = $wpdb->get_var( "
SELECT COUNT(ID)
FROM " . $wpdb->get_blog_prefix( $details['blog_id'] ). "posts
WHERE post_status='publish'
AND post_type='page'"
);
switch_to_blog( $details['blog_id'] );
$blog_list[ $details['blog_id'] ]['name'] = get_blog_details()->blogname;
$blog_list[ $details['blog_id'] ]['desc'] = get_bloginfo( 'description' );
}
switch_to_blog( $current_blog_id );
// Set the Transient cache
set_site_transient( 'multisite_blog_list_details', $blog_list, $expires );
}
unset( $blogs );
$blogs = $blog_list;
}
if ( FALSE === is_array( $blogs ) )
return array();
return $blogs;
}
You can add the following network dashboard widget in the previous plugin to test it out:
add_action( 'wp_network_dashboard_setup', 'dashboard_setup_so_23713801' );
function dashboard_setup_so_23713801()
{
wp_add_dashboard_widget( 'widget_so_23713801', __( 'Test widget' ), 'print_widget_so_23713801' );
}
function print_widget_so_23713801()
{
b5f_print_recent_posts();
}

Categories