I want to strip just the [gallery] shortcodes in my blog posts. The only solution I found is a filter that I added to my functions.
function remove_gallery($content) {
if ( is_single() ) {
$content = strip_shortcodes( $content );
}
return $content;
}
add_filter('the_content', 'remove_gallery');
It removes all shortcodes including [caption] which I need for images. How can I specify a single shortcode to exclude or include?
To remove only the gallery shortcode , register a callback function that returns an empty string:
add_shortcode('gallery', '__return_false');
But this will only work with the callbacks. To do it statically, you can temporarily change the global state of wordpress to fool it:
/**
* #param string $code name of the shortcode
* #param string $content
* #return string content with shortcode striped
*/
function strip_shortcode($code, $content)
{
global $shortcode_tags;
$stack = $shortcode_tags;
$shortcode_tags = array($code => 1);
$content = strip_shortcodes($content);
$shortcode_tags = $stack;
return $content;
}
Usage:
$content = strip_shortcode('gallery', $content);
For me, worked with:
add_shortcode('shortcode_name', '__return_false');
If i try to strip_shortcode, they are remove all shortocodes and changing the final result
If you want to get only the content, excluding any shortcodes, try something like that
global $post;
$postContentStr = apply_filters('the_content', strip_shortcodes($post->post_content));
echo $postContentStr;
Related
I have an page (with snippet code and short code and manual php code) and it call a REST API and base Of response, I want change tag title of this page (Not in database).and it was change every call.
i try do :
in snippet code:
$GLOBALS['MyTitle'] = $response-> title;
in function:
function change_title($title) {
$variable = $GLOBALS['MyTitle'];
if (!empty($variable))
{
$title = $variable;
}
return $title;
}
add_filter('pre_get_document_title', 'change_title',500);
but it was empty every time because the function section run sooner then snippet code(Api Call).
WordPress has not any function for change title tag text? like wp_set_title('my title') to use without add_filter?
Changing title of the page dynamically by applying the filter the hook used for the filter is document_title_parts. Here is the official wordpress documentation link and below is the example. In this example i have used get method for API.
add_filter( 'document_title_parts', 'function_to_dynamic_title');
function function_to_dynamic_title( $title_parts_array ) {
$request = wp_remote_get( 'https://dummyjson.com/products/1' );
if( is_wp_error( $request ) ) {
return $data;
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
$title_parts_array['title'] = $data->title;
return $title_parts_array;
}
Screenshot for your reference
In WordPress, we have an action to change the title programmatically.
add_filter('the_title','your_callback_function');
function your_callback_function($data)
{
global $post;
// add your condition according to page
return 'Desired Title'. $post->ID;
}
I'm trying to accomplish an hard task. The task is removing a echo from a Yoast SEO file using the available WP hooks.
class-frontend.php
public function head() {
global $wp_query;
$old_wp_query = null;
if ( ! $wp_query->is_main_query() ) {
$old_wp_query = $wp_query;
wp_reset_query();
}
/**
* Action: 'wpseo_head' - Allow other plugins to output inside the Yoast SEO section of the head section.
*/
do_action( 'wpseo_head' );
echo '<!-- / ', $this->head_product_name(), ". -->\n\n"; // <-- remove this
if ( ! empty( $old_wp_query ) ) {
$GLOBALS['wp_query'] = $old_wp_query;
unset( $old_wp_query );
}
return;
}
Is there a way to override this function and remove the echo using the available WP hooks? Or is there a better way to do this?
Many thanks.
There is a post at wordpress.stackexchange that indicates you can output buffer using the hooks get_header and wp_head to filter that out:
add_action('get_header', 'ad_ob_start');
add_action('wp_head', 'ad_ob_end_flush', 100);
function ad_ob_start() {
ob_start('ad_filter_wp_head_output');
}
function ad_ob_end_flush() {
ob_end_flush();
}
function ad_filter_wp_head_output($output) {
if (defined('WPSEO_VERSION')) {
$output = str_ireplace('<!-- / Yoast WordPress SEO plugin. -->', '', $output);
}
return $output;
}
That expects your $this->head_product_name() to be / Yoast WordPress SEO plugin. so you may have to alter that...or if you want it to remove "anythere" there, you can change your replacement to something like this:
$output = preg_replace('/<!-- .* -->/Us', '', $output);
But that will remove ALL comments, and it will be slower than the string replace.
Context: WordPress 5.4.5, Yoast 3.7.1
I'm a plugin developer who has access to the client's site. The site has Yoast 3.7.1 installed and I'm wondering if that is significant because no matter what I do I can't change the 404 page's title.
Now on other pages on StackOverflow where similar questions have been posed (here, here and here for example), those answering have asked if the header.php is correctly embedding a call to wp_title(). Here's what's in the current theme's header.php at that point:
<title><?php wp_title( '|', true, 'right' ); ?></title>
Interestingly, in my 404.php page, wp_get_document_title() tells me that the document title is Page not found - XXXX even though the wp_title call above specifies the separator as |. Yoast's rewriting of titles has been disabled so I'm not at all sure where that dash is coming from.
My plugin does a REST call and pulls in content from off-site for inclusion in the page. Part of that content is the text to be used in the title.
On previous client sites, I've been able to do the following:
add_filter('wp_title', 'change_404_title');
function change_404_title($title) {
if (is_404())
{
global $plugin_title;
if (!empty($plugin_title))
{
$title = $plugin_title;
}
}
return $title;
}
However, on this site, that's not working.
I have tried, based on the version of WordPress being used, hooking the pre_get_document_title filter, viz
add_filter('pre_get_document_title', 'change_404_title');
but again to no avail. I am currently reading up on Yoast ...
wp_title deprecated since version 4.4. So we should use the new filter pre_get_document_title. Your code looks fine but I am confused about global $plugin_title. I would rather ask you to Try this first
add_filter('pre_get_document_title', 'change_404_title');
function change_404_title($title) {
if (is_404()) {
return 'My Custom Title';
}
return $title;
}
If it doesn't work then try changing the priority to execute your function lately.
add_filter('pre_get_document_title', 'change_404_title', 50);
How document title is generated has changed since Wordpress v4.4.0. Now wp_get_document_title dictates how title is generated:
/**
* Displays title tag with content.
*
* #ignore
* #since 4.1.0
* #since 4.4.0 Improved title output replaced `wp_title()`.
* #access private
*/
function _wp_render_title_tag() {
if ( ! current_theme_supports( 'title-tag' ) ) {
return;
}
echo '<title>' . wp_get_document_title() . '</title>' . "\n";
}
Here is the code from v5.4.2. These are the filters you can use to manipulate title tag:
function wp_get_document_title() {
/**
* Filters the document title before it is generated.
*
* Passing a non-empty value will short-circuit wp_get_document_title(),
* returning that value instead.
*
* #since 4.4.0
*
* #param string $title The document title. Default empty string.
*/
$title = apply_filters( 'pre_get_document_title', '' );
if ( ! empty( $title ) ) {
return $title;
}
// --- snipped ---
/**
* Filters the separator for the document title.
*
* #since 4.4.0
*
* #param string $sep Document title separator. Default '-'.
*/
$sep = apply_filters( 'document_title_separator', '-' );
/**
* Filters the parts of the document title.
*
* #since 4.4.0
*
* #param array $title {
* The document title parts.
*
* #type string $title Title of the viewed page.
* #type string $page Optional. Page number if paginated.
* #type string $tagline Optional. Site description when on home page.
* #type string $site Optional. Site title when not on home page.
* }
*/
$title = apply_filters( 'document_title_parts', $title );
// --- snipped ---
return $title;
}
So here are two ways you can do it.
First one uses pre_get_document_title filter which short-circuits the title generation and hence more performant if you are not going make changes on current title:
function custom_document_title( $title ) {
return 'Here is the new title';
}
add_filter( 'pre_get_document_title', 'custom_document_title', 10 );
Second way uses document_title_separator and document_title_parts hooks for the title and the title seperator that are executed later in the function, after title is generated using functions like single_term_title or post_type_archive_title depending on the page, and just before the title tags is about to be outputted:
// Custom function should return a string
function custom_seperator( $sep ) {
return '>';
}
add_filter( 'document_title_separator', 'custom_seperator', 10 );
// Custom function should return an array
function custom_html_title( $title ) {
return array(
'title' => 'Custom Title',
'site' => 'Custom Site'
);
}
add_filter( 'document_title_parts', 'custom_html_title', 10 );
Add this to your functions.php
function custom_wp_title($title) {
if ( is_404() ) {
$title = 'Custom 404 Title';
}
return $title;
}
add_filter( 'wp_title', 'custom_wp_title', 10, 2 );
10 - is priority change to overwrite other plugins like SEO
Sorry if my question was basic or stupid but please help me to solve this issue. I'm trying to change <title> and <meta name="description" > tags dynamically in wordpress. so this is what I tried in function.php file.
function changeMeta_2(){
global $wpdb;
$cur_url = $_SERVER['REQUEST_URI'];
$basename = pathinfo($cur_url);
$ebasename = $basename['filename'];
if(is_numeric($ebasename)) {
$url = explode('/', $basename['dirname']);
$basename = explode('.', $url[count($url)-2]);
$ebasename = $basename[0];
}
$pageName = $ebasename;
$arraylist_subcat = array("car","bike","boat","xxxx","yyyy","zzz","mmmm");
$arraylist_maincat = array("aus","ind","usa","uae");
$category_id = get_term_by('slug',$pageName, 'category');
$category_parentid = get_term_by('id', $category_id->parent, 'category');
$parent_slug = $category_parentid->slug;
if ( is_page()) {
if ( in_array($pageName,$arraylist_maincat) ) {
$metaTitle = 'Browse '.$pageName.' | Some txt title | mysite.com';
$metaDescription = 'some of custome blablaaaaa text description '.$pageName.' some of custome blablaaaaa text description ';
echo '<title>'.$metaTitle.'</title>';
echo '<meta name="description" content="'.$metaDescription.'"/>';
}
}
}
add_action( 'wp_head', 'changeMeta_2' );
In the above code I'm trying to change the title tag and meta description for term id which are matching with array values (in_array condition).
Everything works fine, but problem is instead of override(replace) <title> tag is appending in head. Its not changing it appending. please someone help me to solve this issue.
How document title is generated has changed since Wordpress v4.4.0. Now wp_get_document_title dictates how title is generated:
/**
* Displays title tag with content.
*
* #ignore
* #since 4.1.0
* #since 4.4.0 Improved title output replaced `wp_title()`.
* #access private
*/
function _wp_render_title_tag() {
if ( ! current_theme_supports( 'title-tag' ) ) {
return;
}
echo '<title>' . wp_get_document_title() . '</title>' . "\n";
}
Here is the code from v5.4.2. Here are the filters you can use to manipulate title tag:
function wp_get_document_title() {
/**
* Filters the document title before it is generated.
*
* Passing a non-empty value will short-circuit wp_get_document_title(),
* returning that value instead.
*
* #since 4.4.0
*
* #param string $title The document title. Default empty string.
*/
$title = apply_filters( 'pre_get_document_title', '' );
if ( ! empty( $title ) ) {
return $title;
}
// --- snipped ---
/**
* Filters the separator for the document title.
*
* #since 4.4.0
*
* #param string $sep Document title separator. Default '-'.
*/
$sep = apply_filters( 'document_title_separator', '-' );
/**
* Filters the parts of the document title.
*
* #since 4.4.0
*
* #param array $title {
* The document title parts.
*
* #type string $title Title of the viewed page.
* #type string $page Optional. Page number if paginated.
* #type string $tagline Optional. Site description when on home page.
* #type string $site Optional. Site title when not on home page.
* }
*/
$title = apply_filters( 'document_title_parts', $title );
// --- snipped ---
return $title;
}
So here are two ways you can do it.
First one uses pre_get_document_title filter which short-circuits the title generation and hence more performant if you are not going make changes on current title:
function custom_document_title( $title ) {
return 'Here is the new title';
}
add_filter( 'pre_get_document_title', 'custom_document_title', 10 );
Second way uses document_title_separator and document_title_parts hooks for the title and the title seperator that are executed later in the function, after title is generated using functions like single_term_title or post_type_archive_title depending on the page and about to be outputted:
// Custom function should return a string
function custom_seperator( $sep ) {
return '>';
}
add_filter( 'document_title_separator', 'custom_seperator', 10 );
// Custom function should return an array
function custom_html_title( $title ) {
return array(
'title' => 'Custom Title',
'site' => 'Custom Site'
);
}
add_filter( 'document_title_parts', 'custom_html_title', 10 );
For anybody coming to this question in the future: This functionality can be accomplished using the Yoast SEO plugin.
However, if you do want to still do this yourself....
In order to modify the title, rather than the wp_head hook, you need to be using the filters that actually allow you to modify the title: wp_title
And you can / should use the wp_head in order to add the meta description (see the docs here: http://codex.wordpress.org/Meta_Tags_in_WordPress)
Also note there's easier ways to get the page title, mentioned below...
For the title, your code would look something like so:
function changeTitle($title, $sep, $seplocation){
global $wpdb;
// NOTE: This is the HARD way to get the page title, and is unreliable...
$cur_url = $_SERVER['REQUEST_URI'];
$basename = pathinfo($cur_url);
$ebasename = $basename['filename'];
if(is_numeric($ebasename)) {
$url = explode('/', $basename['dirname']);
$basename = explode('.', $url[count($url)-2]);
$ebasename = $basename[0];
}
$pageName = $ebasename;
// NOTE: Why not get pagename this way?
global $post;
$pageName = $post->post_title;
// or if you need the slug...
$pageName = $post->post_slug;
$arraylist_subcat = array("car","bike","boat","xxxx","yyyy","zzz","mmmm");
$arraylist_maincat = array("aus","ind","usa","uae");
$category_id = get_term_by('slug',$pageName, 'category');
$category_parentid = get_term_by('id', $category_id->parent, 'category');
$parent_slug = $category_parentid->slug;
if ( is_page()) {
if ( in_array($pageName,$arraylist_maincat) ) {
$title = 'Browse '.$pageName.' | Some txt title | mysite.com';
}
}
return $title;
}
add_action( 'wp_title', 'changeTitle', 10, 3 );
I want to register a custom length of excerpt on my wordpress plugin. If I add my custom excerpt length on my plugin and if user's theme have another custom excerpt length registered, will they make conflict? I noticed that fucntion name will be different but the filter's tag will be same('excerpt_length').
So, please let me clear about that.
Here is my excerpt length's code.
function custom_excerpt_length( $length ) {
return 40;
}
add_filter( 'excerpt_length', 'custom_excerpt_length');
Thanks.
I use this for a highly customized excerpt output (modified from Aaron Russell's code). It won't conflict with anything else you have. You can remove text values at will. It basically removes any filters for the excerpt output and overrides them.
// better excerpt output
function improved_trim_excerpt($text) {
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace('\]\]\>', ']]>', $text);
$text = preg_replace('#<script[^>]*?>.*?</script>#si', '', $text);
$text = strip_tags($text, '<p>');
$excerpt_length = 40;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, '... [<a href="' . get_permalink(). '" >Read More</a>]');
$text = implode(' ', $words);
}
}
return $text;
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'improved_trim_excerpt');
If you use a function called custom_excerpt_length() and so does the theme, then you could have a conflict on the function name, but not the call to add_filter(). To mitigate the former you can either use an uncomment prefix (myplugin_custom_excerpt_length() for example) or better yet use a class to protect the namespace like $myplugin->custom_excerpt_length().
Adding multiple callbacks to actions/filters in WordPress won't cause a conflict, per se. If there are multiple actions/filters they are run in the order of their priority, which is the third argument to these functions. To give your filter hook a better chance of running last and thus be the value is used, set it to a high priority such as 999 - or at least higher than the function hooked to the filter you want to override, or lower than the default of 10 if you only want to set it if something else does. You can use this same class to add other actions/filters as well.
if ( ! class_exists( 'MyPlugin' ) ):
class MyPlugin(){
private $priority = 999;
private $excerpt_length = 40;
function __construct(){
// Use an array to pass $this and the function to add_filter()
add_filter( 'excerpt_length', array( $this, 'custom_excerpt_length' ) , $this->priority );
}
// The function name won't conflict since it is in the context of $this->excerpt_length()
function custom_excerpt_length( $length ){
return $this->excerpt_length;
}
}
new MyPlugin();
endif; // class_exists()