INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Parse error: syntax error, unexpected T_FUNCTION on plugins page
I have just migrated my localhost WordPress site to my live server using the this tutorial.
For some reason, when I try to activate ANY plugin from within WordPress, it gives me the following error message:
'Parse error: syntax error, unexpected T_FUNCTION in /var/sites/d/sitename.co.uk/public_html/wp-content/plugins/elementor/elementor.php on line 55'
Can anyone give me advice as to why this is happening please? | Seems like you're running an outdated PHP version (lower than 5.3)? You should update the PHP on your server. Best case to PHP 7+ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "fatal error"
} |
Query the title of the page to show posts with matching category in the loop
In the archive page for a custom post type I have this query:
$the_query = new WP_Query( array( 'category_name' => 'Bordeaux' ) );
Then in the loop I have:
if ($the_query->have_posts() );
Et cetera.
The loop correctly searches my posts and displays all posts with the category 'Bordeaux' on the page.
I would like to alter this query so that instead of searching for the text string 'Bordeaux', it will query the title of the page and search for a category with that name.
This will allow me to have just one .php file for all custom post types, rather than individual ones.
I tried the following but it didn't work:
$the_query = new WP_Query( array( 'category_name' => echo the_title(); );
Any help much appreciated! | you don't need to echo the title out.
Try this:
$the_query = new WP_Query( array( 'category_name' => get_the_title() ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, wp query, categories, query posts"
} |
Dynamic assign a custom template to custom post type posts
So I am writing a plugin and I am wanting to assign a custom template that exist within my plugin directory to a registered CPT (features). I have cpt-features-template.php as the file name located in my plugin folder root.
Can I do something like:
add_filter('single_template', function($original){
global $post;
//$post_name = $post->post_name;
$post_type = $post->post_type;
$base_name = 'custom-' . $post_type . '-template.php';
$template = locate_template($base_name);
if ($template && ! empty($template)) return $template;
return $original;
});
Above code referenced from Can I assign a template to a custom post type? | `locate_template` search template only in themes then to use a file outside themes, you can use the filter `template_include` like that
add_filter("template_include", function ($template) {
$post = get_queried_object();
if ( is_single()
&& ("features" === $post->post_type)
) {
// absolute path to the template file
$template = __DIR__ . "/../../template/my_features_template.php";
}
return $template;
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, plugin development, page template"
} |
Conditionally including JS based on whether ACF field is set
I'm trying to include a javascript file in the head of a WordPress page based on whether or not a particular field nested inside a flexible content field nested inside a repeater is set or not.
I can't seem to find anything in the ACF documentation that suggests this kind of functionality is provided. (Someone vaguely mentioned there might be a filter I could use, but I can't seem to find it.) Would I have to write something to query the field outside the loop, or is there a more succinct way of doing this? | The Loop isn't available yet in `wp_enqueue_scripts`, so is_single() etc pp aren't going to work. However, the queried object has already been determined, so you could use something like
add_action("wp_enqueue_scripts", function() {
$qo = get_queried_object();
if(get_class($qo) == "WP_Post") {
if($val = get_field("my-field", $qo->ID)) {
wp_enqueue_script("jquery");
}
}
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "filters, pages, advanced custom fields"
} |
WordPress Plugin Boilerplate: Addition of 3rd party scripts and styles
I am using the Wordpress Plugin Boilerplate (wppb.io) to build a custom plugin and I am not quite sure where to place a 3rd party script and a 3rd party style for a jQuery Timepicker.
Because the timepicker will be used only in the admin area, is it okay to just place the 3rd party files into the `admin/js` and `admin/css` folders respectively, along with my custom scripts and styles for the admin area?
UPDATE: According to top contributer of the boilerplate, Tom McFarlin you suppose to place them inside the respective `css` and `js` folders, so I have marked Samuel's answer as correct. Additionally, Tom states that if we are talking about 3rd party libraries, it would be good to create a `lib` subdirectory inside the `css` and `js` folders and place them there. | **IMO** , since
> the timepicker will be used only in the admin area
, then YES, it is okay you place the 3rd party files into the `admin/js` and `admin/css` folders respectively.
With that, you _(also other developers)_ can be able to clearly know where to find files that corresponds to their respective views.
**Public Folder** : For files that will be used in the frontend
**Admin Folder** : For files that will only be used in the backend. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
Demystifying and understanding shortcode nomenclature
A code snippet from the Tuts Plus →
function link($atts, $content = null) {
extract(shortcode_atts(array(
"to" => '
), $atts));
return '<a href="'.$to.'">'.$content.'</a>';
}
Source Link →
# Question →
How to reproduce `"$to"` in the shortcode?
I tried this →
`[link $to= " But this didnt worked. | It's just `[link to= "
This is a textbook example of why `extract()` is bad. You can't easily tell where variables are coming from. `extract()` creates variables out of an array with the keys becoming the variable name. So this part:
extract(shortcode_atts(array(
"to" => '
), $atts));
Is creating an array with a `to` key, set to ` if it's not defined in `$atts`. Then it's `extract()`ed so that the `to` key becomes `$to`.
You should avoid using `extract()` and just use the `$atts` variable:
function link($atts, $content = null) {
$atts = shortcode_atts(array(
"to" => '
), $atts);
return '<a href="'.$atts['to'].'">'.$content.'</a>';
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development, shortcode"
} |
Wordpress Multisite - Auto enable theme
I have a server that uses themes from our private repository, and I'd like to auto enable the themes as soon as they exist in the wordpress themes folder.
Right now I have to login as administrator and enable the theme network-wide so the adminisrators can choose the theme.
Is there a way to configure wordpress network to AUTO enable the themes? | Unfortunately, no. For something like that to work, WordPress (or some plugin to do that) would need to scan themes folder for changes, and that can be performance intensive operation. Maybe with some sort of scheduled scan running every few minutes.
I am not aware of any plugin that can do that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, themes, network admin"
} |
Check if post has children or not
I need some code to know if the post has another pages or not
unfortunately i didn't find yet now any reference for this so any idea will be appreciated
What I need to acheive is
if has child
//some staff
else:
// another staff
now I am using
$args = array(
'post_parent' => get_the_ID(), // Current post's ID
);
$children = get_children( $args );
// Check if the post has any child
if ( ! empty($children) ) {
// The post has at least one child
echo 'yes';
} else {
// There is no child for this post
echo 'no';
}
but any post have featured img returning yes and if used `post_type=post` in args all posts returned no even if have child | You can first attempt and get a list of post's children. If the returned value was empty, then the post has no child. Here's how you do it:
$args = array(
'post_parent' => get_the_ID(), // Current post's ID
);
$children = get_children( $args );
// Check if the post has any child
if ( ! empty($children) ) {
// The post has at least one child
} else {
// There is no child for this post
} | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 4,
"tags": "posts, children"
} |
How to restrict wp generate attachment metadata() to certain intermediate image sizes
In Wordpress, we have added our own intermediate image sizes to the standard Wordpress sizes using add_image_size().
Using our own admin interface to upload images, we then use wp_generate_attachment_metadata() to create all thumbnails and save them to a predefined folder on the server.
However, we would like to restrict wp_generate_attachment_metadata() to generate our custom defined image sizes ONLY and ignore the Wordpress standard sizes.
Is this possible?
Thanks in advance for any help! | `wp_generate_attachment_metadata()` uses `get_intermediate_image_sizes()` to get the sizes to work on, which makes them filterable via `intermediate_image_sizes`.
Additionally, you can filter them after cleanup with `intermediate_image_sizes_advanced`, the result should be the same. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, plugin development, uploads, thumbnails"
} |
Insert HTML content in WP Query at specific point
I have a category page with an `if ( have_posts() ) : ?>` loop and would like to insert HTML content after the nth post.
I've done this previously with a WP_QUery using an `if( $query->current_post == 4 )` statement.
How can I achieve the same effect with a `have_posts` loop?
Thanks. | The global $wp_query is the default query you're working on when you use `have_posts()`, `the_post()` etc, so just add
global $wp_query;
if($wp_query->current_post == 4) echo "4!";
global might or might not be necessary (and is certainly only necessary once, so just add it before the while loop), it depends whether you're in the original template or in a template that has been included via a function call. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, theme development, loop"
} |
All Posts admin screen - show time underneath the 'Date'?
In the list of posts in the 'All Posts' screen, is there a way to display both date -and- time in the Date column? If you hover over the date, the time is part of abbr tag title, but I'd like to display the time, directly. I see that I could unset the current Date column and put in a custom Date column. Just wondering if there is a simpler solution to show the time, since it's already there in the abbr tag? | Add this code to `functions.php` of your active theme:
function wpse_posts_list_date_format( $time, $post ) {
return $post->post_date;
}
add_filter( 'post_date_column_time', 'wpse_posts_list_date_format', 10, 2 );
The callback function receives 4 parameters, but we need only 2. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "posts, admin"
} |
multiple where condition in result query
I am trying to get data with multiple where condition but i do not where is problem .this query sending blank out put.any help.
$user1 = $wpdb->get_results("select product,checked_by,submit_date,unit_data,temperature_in,temperature_out,time_in, time_out,category from diary_user_form_storage where category_name='opening OR closing' order by submit_date"); | Your syntax for where is wrong it should be
$user1 = $wpdb->get_results("select product,checked_by,submit_date,unit_data,temperature_in,temperature_out,time_in, time_out,category from diary_user_form_storage where category_name='opening' OR category_name='closing' order by submit_date"); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, mysql"
} |
How to auto login user again after change user_login
I have a system work by ajax that is change user_login of users and this is my code:
$wpdb->update($wpdb->users, array('user_login' => sanitize_text_field($args['user_login'])), array('ID' => $user_id));
After user_login is changed WordPress is log out this user so I try to use wp_signon after user_login changed but it's not working, Any advice? | I found when attempting similar I needed to clear the user cache to get the relogin to work (after much frustrating testing!):
wp_cache_delete($user_id, 'users');
wp_cache_delete($old_user_login, 'userlogins'); // maybe unnecessary?
$creds = array('user_login' => $user_login, 'user_password' => $user_password, 'remember' => true);
wp_signon($creds);
Note for this to work you may also need the user to change their password at the same time so that you can populate the `$user_password` field with a plain text password to provide to `wp_signon` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "php, database, users, sql"
} |
get avatar from facebook graph
I use this plugin to get fb connect
wordpress.org/plugins/nextend-facebook-connect/
the problem is I need to show avatar from FB graph that stored on database. when I use this plugin wordpress.org/plugins/sidebar-login/ this plugin can show the fb avatar perfectly. now I just need to create some coding that can call that avatar image.
when I use this: get_avatar is show misterius man avatar, not fb why, my question is sidebar-login plugin can show the fb gtaph avatar use same tag "get_avatar"
get_avatar( $this->user->ID, apply_filters( 'sidebar_login_widget_avatar_size', 38 ) )
this is confusing me, sorry please help
Note: i need show avatar in content page but I show that use custom template page with php code. thanks! | I found the solution!
global $current_user;
get_currentuserinfo();
echo get_avatar( $current_user->ID, 48 ); | stackexchange-wordpress | {
"answer_score": -1,
"question_score": -1,
"tags": "facebook, avatar"
} |
How to stick the footer to the bottom of the page?
I need the site footer to sit across the bottom of the site at all times.
Currently, it sits across the site bottom when there is content on the page, but with no content on the page it (.site-footer) rises from the bottom to the middle of the visible page as represented in this image:
` ;
wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css' );
I am using the above method to enqueue stylesheet, but what I want is not achieved.
Whatever I write in `responsive.css` should be prioritized(that means CSS written here should override everything else written in style.css.), but that is not happening. Is there a way to achieve it through something that WordPress provide?
# Update →
the whole idea is not to use `!important`, but still when the website is loaded in smaller screens than responsive.css should dominate or override style.css without using any `!important` tag. | If you want to make sure the second stylesheet loads after the first, you can use the third argument of `wp_enqueue_style` to set a dependency, eg:
wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css', array() );
wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css', array('styles') );
As for having **all** the styles in _responsive.css_ override _style.css_ , that is going to entirely depend on the specificity of the targeting in each stylesheet, CSS being a Cascading Style Sheet, it would be worth researching exactly what that means if you aren't fully sure how it works. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 0,
"tags": "php, functions, css, wp enqueue style"
} |
How to apply style_loader_src filter with exclusion of a specific file?
I am trying to remove query string from all scripts and styles files except on a specific with handle name `child-style` file but keep getting error of
> Missing argument 2 for _remove_q_strings()
with the following code
function _remove_q_strings($src, $handle){
if($handle != 'child-style'){
$src = remove_query_arg('ver', $src);
}
return $src;
}
add_filter( 'script_loader_src', '_remove_q_strings', 15, 1 );
add_filter( 'style_loader_src', '_remove_q_strings', 15, 1);
Why giving me this while those two arguments a defined in the `apply_filters` here | The last value of add_filter sets how many arguments are passed to your function. You can pass two arguments like this:
add_filter( 'script_loader_src', '_remove_q_strings', 15, 2 );
add_filter( 'style_loader_src', '_remove_q_strings', 15, 2 );
More details in the codex | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development"
} |
Renamed plugin folder and when I changed back nothing was activated
To test why a few plugins where not working I had created a new folder and moved 95% of my plugins into that folder named: plugins-null. Well after I visited my site admin and figured out it wasn't any of my other plugins effecting the issues I went in and used the new folder named plugins-null and just changed its name to plugins and deleted the old plugin folder. Well when I visited my admin area again all of my plugins were there but none were activated. I have a multisite with 89 plugins I would hate to have to reactivate them all.
Am I missing something? Any ideas where I went wrong? | Typically when you visit the actual _plugins page_ in admin with the folder renamed it will detect this and deactivate missing plugins by updating the `active_plugins` option... otherwise it will leave the option intact and unchanged. At least on single site, I am not fully sure on multisite if anything else triggers this update.
However if you have a backup of your database, you _should_ be able to retrieve the `active_plugins` option and reapply it through say phpMyAdmin. Again this may be different for multisite (though I don't think it is, just doing it for the correct table should be all you need.) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, multisite"
} |
Understanding the query string after .htaccess rewrite
I'm of the understanding that Wordpress' .htaccess, like below:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
sends all queries through to the index.php (unless the filename exists on the server etc).
So, if I go to ` Wordpress rewrites that as `
But what I don't understand is that I have, at the top of a page template
<?php print_r($_GET) ?>
and when I navigate to ` that returns `Array()`. I'd expect something like `Array('pagename' => 'checkout')`;
How can I access the variables that Wordpress uses when handling a URL? | It's not really rewriting the URL in the conventional sense, URL parsing happens entirely within PHP.
You can access the query vars in the global `$wp_query->query_vars`, or with the `get_query_var` function.
Also note that `parse_request` is the earliest action where this info will be available. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "url rewriting, urls"
} |
Wordpress How to begin editing from admin page (please see picture)
I have searched the internet but I can't seem to find the answer- is my page not set up to be edited online ? or am I missing something. Do I need to download to begin editing?
Picture below I think explains my issue ! Any information would be helpful thank you !!\[enter image description here]1 | This is the dashboard for the Subscriber user roles, and it allows only editing of own profile. Editor, author and administrator roles can create/edit posts.
Are you sure you have an account with high enough role to create posts? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "admin"
} |
How can I show an empty WooCommerce cart?
I've made a single-page checkout template for donations. The donation plugin is attached to the cart and will update the cart properly, however the cart will not display on my page if 0 items are in the basket when the user arrives. The intended end user will generally have no items in their cart.
How can I force the WooCommerce cart to show up if there are no products in the cart? | `global $woocommerce; $count = $woocommerce->cart->cart_contents_count;`
This should be the variable you'd want to work with. Try `var_dump` on this to display its value. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "woocommerce offtopic, templates, hooks"
} |
Force login for a subdirectory within wordpress install
I am using a simple force login plugin that works great "Force Login By Kevin Vess".
I have a subfolder (right now in /wp-content/subdir/") that i want to also force login for but cant figure how.
Is there a way to accomplish this? | This was easier than i thought
<body>
<?php
chdir( '../' );
include 'wp-load.php';
if ( is_user_logged_in() ) : ?>
// Do stuff
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "login"
} |
Call add_action() in function wordpress
I have a problem with a WordPress hook. I want to call an action in another actions callback, but it doesn't seem to work. I want to call `add_meta_tag` action only if the page is saved. This is what I have:
function saveCustomField($post_id)
{
add_action( 'wp_head', 'add_meta_tag' );
}
add_action( 'save_post', 'saveCustomField' );
function add_meta_tag(){
echo "TEST";
}
How can I get the above to work properly? | You're thinking about this entirely wrong. A meta tag isn't something you add when a post gets saved, it's something that gets added to the output when a post is _viewed_.
So instead of trying to hook the action inside `save_post`, you hook it on every page load, and _inside_ the hook you check if your custom field exists on the post being viewed. If it is, you output the tag.
function wpse_283352_add_meta_tag() {
if ( is_singular() {
$post_id = get_queried_object_id();
$meta = get_post_meta( $post_id, '_my_custom_field', true );
if ( $meta ) {
echo '<meta name="my_custom_field" content="' . esc_attr( $meta ) . '">';
}
}
}
add_action( 'wp_head', 'wpse_283352_add_meta_tag' );
That function just goes in your plugin file/functions file, not inside any other hook. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "actions, save post"
} |
woocommerce 3.2.1 not sending order notification emails
Why woocommerce 3.2.1 not sending order notification emails to gmail, yahoo , ... I have tested many ways to solving this problem like using smtp, disabling active plugins, testing other themes , ... But nothing works and now I have installed older version (2.6.14) and is sending emails to inbox and works good. I need latest version and need to fix it up. Help me! | Finaly got it! if you have my problem you can do following steps to make it work: install Easy WordPress SMTP. It the only one that works.
And do what is said in this link : < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, php, woocommerce offtopic"
} |
Using custom HTML tags to WordPress
Similar to, for example, `<blockquotes>`, I also work with, for example, custom `<blocktips>` styled with :before and :after elements to be used regularly on a site. After styling, these are added in the Text editor as `<blocktip>Text here</blocktip>`.
The problem is that when I go back to the Visual editor, these elements are removed from the code and has to be added again before Updating.
In my case, is there a way to prevent the WordPress editor from removing these custom HTML tags. | You can expand list of KSES allowed tags (and their attributes):
add_filter('wp_kses_allowed_html', 'wpse_283385_blocktip_tag');
function wpse_283385_blocktip_tag($allowed_tags) {
$allowed_tags['blocktip'] = array(
'name' => true,
'id' => true,
'class' => true,
'style' => true
);
return $allowed_tags;
}
add_filter('tiny_mce_before_init', 'wpse_283385_blocktip_tag_tinymce');
function wpse_283385_blocktip_tag_tinymce($init) {
$tags = 'blocktip[*]';
if ( isset( $init['extended_valid_elements'] ) ) {
$init['extended_valid_elements'].= ','.$tags;
} else {
$init['extended_valid_elements'] = $tags;
}
return $init;
}
If you need more attributes for that tag, add them in the array in the first function, or add them to $tags (comma separated) in the second. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "html, editor, css"
} |
Passing user enetered value in widget: number of words, for example
<a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a>
The above is the code snippet from one of the widgets of my theme.
Now in the widget arrangement, this is the situation →
$instance['number_of_words'] = absint( $new_instance['number_of_words'] );
the above setting is to handle how many numbers of words do we wish to show in the title?
how should we pass this variable `$instance['number_of_words']` →
<?php the_title(); ?> | You can't pass this variable to `the_title()` but you can simply wrap it in wp_trim_words function.
`echo wp_trim_words( get_the_title(), $number_of_words );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, widgets, widget text"
} |
Get and show all of the available categories
I know that there are a few ways of doing this but for everything that I have tried I can only manage to get the first category. For example:
<?php echo get_the_category_list(); ?>
Only shows one. Like:
<?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
Shouldn't this functions get me the full list of existing categories? | It should be noted that both
<?php echo get_the_category_list(); ?>
and
<?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
display ALL categories that are assigned to the current post in the loop.
From your question's title, I understand that you want to display all available categories that exist in the website, so `wp_list_categories()` is more suitable. So using:
<ul>
<?php wp_list_categories(); ?>
</ul>
will return a list of all categories that have been assigned to at least one post. You can see the documentation for the function here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
How to set permalinks when posts and pages have different URL structures?
I've been hired to migrate a custom CMS to Wordpress.
The blog page is a subpage of "About Us": `/about-us/blog/`
Each blog post has a URL of `/about-us/blog/xxxx/postname`, where xxxx is the year it was posted.
The site has 10 parent pages, each having `x` sub-pages, so I need webpages to have a URL of `/parent-page/sub-page`
Is it possible to set permalinks that will work for both webpages and blog posts with the above URL structure? TIA. | From quick test you _should_ be able to just use Custom Structure for it (in Settings / Permalinks):
/about-us/blog/%year%/%postname%/
I am not _entirely_ sure it won't conflict with pages, but it seemed to have worked in my dev install. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "permalinks"
} |
Align reCaptcha to right on Contact Form 7
I am running a wordpress site with contact form 7. I have signed up to reCaptcha and everything is working fine except all the fields on the form are right aligned but the reCaptcha is aligned to the left.
Is there anyway to align it to the right like the rest of the fields?
Heres a screenshot from my local machine: ;
function mysite_opengraph_content($val){return '<img src=" alt="Rafaël De Jongh - Web Developer | 3D Artist"/>' . $val;}
However this doesn't seem to work anymore, does anyone know a different way to solve this like it did in the past with above mentioned code?
Or in a way to improve upon this code I mocked up:
function default_opengraph(){return '
add_filter('wpseo_opengraph_image','default_opengraph');
add_filter('wpseo_twitter_image','default_opengraph');
But which allows to add this to the OG:Images rather than replace it. | The action that allows an OG image to be added seemed to be the thing I was looking for, so much for proper documentation on their side. But now the only thing I'm wondering if the following code I made up is the proper way to deal with it:
$default_opengraph = '
function add_default_opengraph($object){global $default_opengraph; $object->add_image($default_opengraph);}
add_action('wpseo_add_opengraph_images','add_default_opengraph');
function default_opengraph(){global $default_opengraph; return $default_opengraph;}
add_filter('wpseo_twitter_image','default_opengraph');
As well as this one doesn't add additional twitter:images but as far as I know there should also only be one for this.
But at least it's a "solution" to my question rather than down voting this question, I would've loved to hear some feedback on it! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, hooks, tags"
} |
Best way to query posts and order by relevancy to query
I want to query a custom post type that has 100+ associated categories. The query will be based on values in the current user meta, specifically, the user will have preselected categories they want to see.
What is the best way to do the query that: returns all posts that match at least one category while ordering by post with the most number of categories matching the user preference? | I don't think this can be cleanly expressed in WP query API. YOu can query for posts matching _all_ of terms in a set or _any_ of terms in a set, but there is no concept of _how many_ terms matched.
You would need to write either:
1. Very custom SQL for the query you want which will implement the counting.
2. Query loosely everything that matches and do the coun on PHP side after getting results. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, user meta, order"
} |
Getting array of customizer settings
I'm adding custom options to my theme using the customizer api. For example:
$wp_customize->add_setting( 'header_textcolor' , array(
'default' => '#000000'
) );
$wp_customize->add_setting( 'footer_textcolor' , array(
'default' => '#333333'
) );
Is it possible to return an array of all my custom settings from customizer? | Yes. You can get an array of all registered settings via `$wp_customize->settings()`. If you want to display them all you could do this:
if ( is_customize_preview() ) {
global $wp_customize;
$theme_mods = array();
foreach ( $wp_customize->settings() as $setting ) {
if ( 'theme_mod' === $setting->type ) {
$theme_mods[ $setting->id ] = $setting->value();
}
}
echo '<pre>' . json_encode( $theme_mods, JSON_PRETTY_PRINT ) . '</pre>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, theme customizer"
} |
How to migrate a website based on a custom database to wordpress?
My question is similar to that one which was closed for being too broad, so I'll try to be clearer.
**What I have** : a sqlite database (single table) containing over 50'000 posts (with fields like author, content, date, etc.). It stems from scraping a huge static, html-only website.
**What I want to achieve** : displaying those posts in a standard WP installation.
**My approach** : I would
1. Initialize an empty WordPress website
2. Write a script that reads a post from the original DB and writes it into the corresponding fields of the WP database (ID -> ID, author -> author, date -> date, ...)
3. Run the WordPress engine engine and expect the posts to appear
**My question** : is this approach likely to succeed, or should I avoid this futile work and consider other solutions? | I don't see any reason for this not to work. I have done similar transfers few times, and if you transfer all data correctly, and if posts in the wp_posts are well formed, with all data present (status, type...), it will work.
The tricky part might be the data that can't fit into wp_posts, and it should go into wp_postmeta, you need to take care of proper post ids. Also, make sure to use correct format for date field, make sure to have both post_date and post_date_gmt filled, guid (some unique string for each post, WP uses URL by default), and make sure author ID's are correct. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "database"
} |
wp_editor is not rendering shortcode
I have created a dashboard widget and this widget will show content which i'll add from an specific page. So, i created a option page and made a textarea field with wordpress editor.
wp_editor(html_entity_decode(stripcslashes($widget_content)), 'widget_wp_content');
But when i am calling this field value in widget area than its giving correct image as image not image html. But for caption its showing caption shortcode.like
[caption id="attachment_25613" align="alignnone" width="200"]image display and caption_content[/caption].
I am using code to print value is
echo html_entity_decode(stripslashes($val['content']));
Thanks | You need to run it through `do_shortcode()`. `do_shortcode()` 'runs' any shortcodes in text passed to it:
echo do_shortcode( html_entity_decode( stripslashes( $val['content'] ) ) ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "widgets, dashboard, wp editor"
} |
Display product variations on same row
I'm having trouble displaying variations on the single product page in woocommerce. I would like to show the product variations on the same row and not separate, like the attached pic.
`?
'category__in' => array($category->term_id)
Does that mean this query would include array of all category id?
Thank you. | The variable **$category** is a single category (has to be set somewhere before), and the **$category->term_id** is the ID of that category.
And, **array($category->term_id)** is an array with one element only, and that element is category ID. **'category__in'** argument requires an array of categories, and if you have one category even, it has to be placed in the array.
So, this query will include all posts belonging to a single category, defined by the **$category** variable. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom taxonomy, terms, categories"
} |
Auto delete comment if Contains
How to Auto-Delete comment if contains certain string?
i tried with this but not work:
add_action( 'transition_comment_status', 'my_approve_comment_callback', 10, 3 );
function my_approve_comment_callback( $new_status, $old_status, $comment ) {
if (strpos($comment->comment_content, 'dog') !== false) {
wp_delete_comment( $comment->comment_ID, true );
}
}
I have also tried with:
wp_list_comments('callback=better_comment');
function better_comment($comment, $args, $depth) {
if (strpos($comment->comment_content, 'dog') !== false) {
wp_delete_comment( $comment->comment_ID, true );
}
}
Nothing work =( | It is better to use 'comment_post' action for this purpose, it is fired when the comment is saved in database:
add_action('comment_post', 'my_comment_post_callback', 10, 3);
function my_comment_post_callback($comment_id, $comment_approved, $commentdata) {
if (strpos($commentdata['comment_content'], 'dog') !== false) {
$post_url = get_permalink($commentdata['comment_post_ID']);
wp_delete_comment($comment_id, true);
wp_redirect($post_url);
exit;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments, hooks, spam"
} |
Show current user posts in custom post type query
I have a custom post type named `'saved-orders'`, and I want to edit the main query so the current user logged in only sees their posts.
I've added this to my `functions.php` but it's still displaying the posts from all users:
add_action( 'pre_get_posts', 'custom_query_vars' );
function custom_query_vars( $query ) {
global $current_user;
if (!is_admin() && $query->is_main_query()) {
if ( get_post_type() == 'saved-orders' ) {
$query->set( 'author' => $current_user->ID );
}
}
return $query;
}
Can anyone help me please? | There are 2 fundamental problems here:
## Problem 1
`pre_get_posts` lets you modify a query before it happens, and in this case you're modifying the main query before it happens.
But you do this:
if ( get_post_type() == 'saved-orders' ) {
`get_post_type` shouldn't work here as it's too early, the main query hasn't happened yet. Instead, lets ask the query object:
if ( 'saved-orders' === query->get( 'post_type' ) {
## Problem 2
This is a syntax error, and not valid PHP:
$query->set( 'author' => $current_user->ID );
`=>` is only used in 2 situations:
array(
'key' => 'value'
)
and
for ( $array as $key => $value )
Neither of which are function calls. The correct way to call the `set` method is:
$query->set( 'queryvar', $new_value );
With some beginner level PHP knowledge you should now be able to fix your filter. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, php, functions"
} |
What is the difference between WordPress Business plan vs self hosted WordPress (WordPress developer perspective)?
**Short version of question** : : I am not asking the difference between WordPress.com vs WordPress.org.... I am asking difference between WordPress.com Business plan vs WordPress.org
**Long version of question** :
> According to < **WordPress business plan allow to install third-party themes and plugins**.
So what is the difference between WordPress Business plan vs self hosted WordPress?
In other word, what are the limitation (WordPress developer perspective) of WordPress Business plan when comparing self hosted WordPress? | First it is important to note the difference between _Business Plan_ and regular WordPress _com_. To my knowledge _Business Plan_ accounts are _not_ hosted on regular dot com grid, but are based on infrastructure of more conventional managed hosting company they've acquired (not sure if completely) while back.
So the closest analogue for it would be a _managed_ hosts that specialize in hosting WordPress, being _more managed_ on a scale and offering some cross-integration with dot com functionality.
Their support materials cover nuances of Business Plan in detail.
In a nutshell difference with _less managed_ self–hosted site seem to be:
* no direct filesystem access (no arbitrary file edits);
* black list of some plugins that are not allowed;
* additional features related to dot com offers;
* ability to migrate to/from regular dot com grid.
Overall I would call it _highly managed_ WP hosting solutions, which is aimed more at site owners than developers. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wordpress.com hosting, wordpress.org"
} |
Get userdata from url
I want to make a custom profile page.
So I would set a link from posts page using a simple hook, get the author, then a something like
<a href="www.website.com/profile/<?php the_author(id); ?></a>
But how do I then retrieve this id from url for a profile page?
Get_var? or Get_object?
I would then want to display the users name, address, and other posts (custom post type) by the author.
Thank you | Wordpress already has a url structure for Author information. If you have pretty Permalinks enabled, the URL should read like < .
You can make a new template file named author.php in your theme to manipulate what is shown on this page (add meta information and whatnot).
You can get the author id in the author.php by using `get_queried_object_id()` . Bonus: all the posts by this author are in the loop.
To get the URL for the authors page, you can use `get_author_posts_url( $author_id)` . | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "urls, user meta"
} |
Return get_header and get_footer string instead of echo it
I am trying to use mustache within a wordpress application and modularize it. I would like to use mustache partials to inject the header and footer string into individual template files.
However, as soon as I call get_header / get_footer on the controller layer, the header and footer are echo'ed out immediately. What I am trying to do is just retrieve the markup from the header and footer and store it into a variable, for 'later' injection into the template is this possible?
Thanks in advance! | Use an output buffer!
ob_start();
get_header();
$header = ob_get_contents();
ob_end_clean();
The header is now in `$header` and you can do with it as you please. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "templates, headers, footer"
} |
How can i trigger an action manually?
I'm currently working with a Learn Management System and students can earn certificates after they completed a course. This certificate gets generated and has an "action hook" hooked to it, so i can hook in to modify it. My problem is now with the debugging: Every time i want to test my hook i have to create a user and let them complete the course. Has anyone an idea how to trigger the action manually? This would reduce the debugging time drastically. Thank you | Use do_action, you can just:
do_action( 'my_action');
if your action has a callback function that need arguments say:
function my_callback( $an_array ){
//use the array for something here
var_dump($an_array);
}
add_action( 'my_action', 'my_callback' );
you can specify it in the `do_action` like this:
do_action( 'my_action', array( 'array_for_callback') ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "hooks, actions"
} |
Is there a way to add a custom text + link above search results for different searches?
Do any of you know a way to customize what displays on a search result page for different individual searches? I am open to doing this through code, a free plugin, or a premium plugin.
Context: I run a small college's Wordpress website. Sometimes users search for something that is on another site. Example: If someone searches for "athletics," I need to be able to point them to our non-Wordpress athletics site. I would like to be able to add "Visit our athletics site (link)" to the search page, but only when the query is "athletics." | You can do it with if-condition, example:
if( get_search_query() == 'athletics' ){
echo 'Visit our athletics site';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "search"
} |
Cannot locate wp_footer() included scripts
Pulling my hair out here trying to locate the code being invoked by the wp_footer() hook.
The following Google Analytics code doesn't seem to be located in any of the files in my entire web directory. None of the theme files. None of the WordPress files. Nowhere to be seen.
` only, but I can't seem to add custom post types `!is_singular()`. Here's the code:
if ( !is_page(array('my-resumes','resume-listings', 'submit-job', 'submit-resume', 'job-alerts', 'job-listings', 'my-jobs', 'my-bookmarks' ) ) || !is_singular( array( 'job_listing', 'job' )) ) {
// disappear some stuff | You should use `&&` instead of `||`.
Like:
if ( !is_page(array('my-resumes','resume-listings', 'submit-job', 'submit-resume', 'job-alerts', 'job-listings', 'my-jobs', 'my-bookmarks' ) )
&& !is_singular( array( 'job_listing', 'job' )) ) {
// disappear some stuff | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "conditional tags"
} |
Stuck In a Redirect Loop
I'm trying to build a code where non-members get redirected to the landing page. Unfortunately, the code that I've built works partly and results in a redirect loop.
if(is_user_logged_in() && function_exists('pmpro_hasMembershipLevel') && pmpro_hasMembershipLevel()) {
global $current_user;
$current_user->membership_level = pmpro_getMembershipLevelForUser($current_user->ID);
echo 'Membership Level: ' . $current_user->membership_level->name;
} else {
wp_redirect(/my-account/orders/);
exit;
}
Any help would be appreciated. The first part of the if statement is working fine but the second half is returning redirect loop.
Thanks and Regards,
Piyush | You also need to check if the user is on that particular page or not. If he is on that page, then there is no need to redirect him/her again.
Change your else to this:
if(is_user_logged_in() && function_exists('pmpro_hasMembershipLevel') && pmpro_hasMembershipLevel()) {
global $current_user;
$current_user->membership_level = pmpro_getMembershipLevelForUser($current_user->ID);
echo 'Membership Level: ' . $current_user->membership_level->name;
} else {
if( ! is_page('page-slug') ){
wp_redirect('/my-account/orders/');
exit;
}
}
In which `page-slug` is the slug of the page you are redirecting your users to. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "redirect, wp redirect"
} |
dynamic page in WordPress
Hi i need some advise as a newbie, I have a table of brands in database and page with all brands icon when i click in a brand icon i want to be redirected to a dynamic page that load content from database according to the brand icon i clicked
I want to know if is it possible to do it in WordPress and if it's better than static pages and if there is any plugins i can use?
Thank you in advance | Since the `wp_brands` is your own custom table, I would recommend passing the brand the user clicks on via Query String:
You can access this via PHP in your page template(not the wp-admin editor) like this:
$_GET['brand'];
Once you have that you can use whichever brand the user chose to query the database. This isn't the "WordPress" way of doing things, but it will solve the issue. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php"
} |
Hide tab Buddypress profile for visitors, not logged in users
my code below works like a charm for logged in users to hide certain tabs:
function bpfr_hide_activity_nav() {
if( !current_user_can( 'subscriber' ) ){
return;
}
bp_core_remove_nav_item( 'media' );
bp_core_remove_nav_item( 'forums' );
bp_core_remove_nav_item( 'orders' );
bp_core_remove_nav_item( 'activity' );
}
add_action( 'bp_ready', 'bpfr_hide_activity_nav' );
But for visitors/logged out users, the tabs are still visible in the members profile where role is set to Subscriber. My code is based in current_user_can, how can I transform this into profile-I-see-on-page-has-to-be-effected option?
Hope someone can point me in the right direction. Thanks. | I think the function you are looking for is `bp_displayed_user_id()`. That will get the ID of the user whose profile is currently being displayed.
Then, you can check their role like this:
$user = get_userdata( bp_displayed_user_id() );
if ( ! in_array( 'subscriber', (array) $user->roles ) ) {
return;
}
You could also use `user_can()`, but it is best to avoid using role names with `user_can()` and `current_user_can()`, as they are really designed for capabilities and not roles. In fact, you ideally would not check user roles in a case like this at all. It would be better to add a custom capability to certain roles, like `'extended_bp_profile'`, and then check for that instead. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, buddypress, profiles"
} |
Allow contributor to edit own posts after published, without plugin
I would like to allow contributors to edit (only) their own posts after it has been published. I would like to do this without any plugin and only for a certain custom post type. I cannot seem to find such a code.
Can anyone help me out? Thanks | you can add the capability `edit_published_posts` to your `contributor` role and this will do what you are after.
> edit_published_posts Since 2.0 User can edit their published posts. This capability is off by default. The core checks the capability edit_posts, but on demand this check is changed to edit_published_posts. If you don't want a user to be able to edit their published posts, remove this capability. (see also this comment on the Role Manager Plugin Homepage).
And the code to do this is very simple.
function add_theme_caps() {
$role = get_role( 'contributor' );
$role->add_cap( 'edit_published_posts' );
}
add_action( 'admin_init', 'add_theme_caps');
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Can I authenticate with both WooCommerce consumer key and JWT?
I want to authenticate against _both_ :
* the WooCommerce consumer key, for system queries _and_
* JSON Web Tokens (JWT), for user queries
I have installed JWT Authentication for WP REST API. But after activating the plugin, previously working queries (that use the WooCommerce consumer key for authentication) fail with:
{'code': 'jwt_auth_bad_auth_header',
'data': {'status': 403},
'message': 'Authorization header malformed.'}
How can I configure Wordpress / the JWT plugin so that they succeed? | Yes this is possible by structuring your requests appropriately.
For system requests use OAuth 1.0 (consumer key as before), but encode it to include the OAuth credentials _in the URL_ not in the headers. Having the OAuth credentials in the `Authorisation` header triggers the JWT error.
GET
* Authorization: `OAuth 1.0`
* Consumer key: FILLED IN
* Consumer secret: FILLED IN
* Other fields: blank
* Headers: blank
* Body: blank
To request a token (for a user-based query), you don't use authorization, you include the user credentials in the body:
POST
* Authorization: `No Auth`
* Headers: blank
* Body: `form-data`
* key: username, value: test
* key: password, value: test
Once you have the token, you can add it to the `Authentication` header per JWT requirements.
To test these queries, it's easiest to use a dedicated tool like httpie or Postman.
**Reference:** < | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "rest api, authentication"
} |
How can I authenticate user credentials against a Wordpress instance?
I am running a second web application in addition to Wordpress/WooCommerce. When users log into the second application, I'd like to authenticate them against the WP instance. I am using the REST API for data queries, but that only allows authentication with a consumer key. The API doesn't provide endpoints for user authentication.
Given a username and password, how can I authenticate against a Wordpress/WooCommerce instance? (In other words, from outside the instance.) | The JWT Authentication for WP REST API plugin offers a user authentication mechanism. You will need to:
* install and configure the plugin
* make user authentication requests against the new token endpoint
* optionally use the token to make further queries on behalf of users
* continue using OAuth 1.0 for WP/WC REST queries
**References:**
* <
* Using JWT to authenticate a user with an external system?
* JWT authentication with WP - Approach | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "users, rest api, authentication"
} |
Expand author, tags and categories in the Wordpress JSON API
In the V1 of the Wordpress JSON API when you got a list of posts you would also get details of the author, tags and categories.
But in V2 it seems you just get the ID and would need to do another request to get more info.
Is there a way around this, such as a query parameter to automatically expand certain things?
Here is what V1 would return:
tags: {
FM: {
ID: 153647,
name: "FM",
slug: "fm",
description: "",
post_count: 68,
},
FM17: {
ID: 130762795,
name: "FM17",
slug: "fm17",
description: "",
post_count: 31,
}
}
Here is what V2 returns:
tags: {
153647,
130762795
}
At the moment it's not clear if there is any benefit to using V1 over V2 of the api, V1 would infact be easier in this instance. | I figured this out, you have to add _embed=1 to any request so:
> /posts?_embed=1&orderby=date&order=asc
for instance.
Then it will include an `_embeddable` key. Annoyingly all the terms come under here so you have to do some extra work to extract the difference between tags and categories etc. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "api, rest api"
} |
get_template_part not working with ajax
I loaded some contents by ajax, When i try something like this:
$resp = array(
'success' => true,
'data' => 'the content here'
);
it's working without any issues but if i used something like this:
$resp = array(
'success' => true,
'data' => get_template_part( 'templates/update', 'profile' )
);
it gives me SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data.
the content here{"success":true,"data":null}
What's the problem with get_template_part? | `get_template_part()` includes the PHP file, which will break `$resp`. You need to use output buffering to capture the output into a variable:
ob_start();
get_template_part( 'templates/update', 'profile' );
$data = ob_get_clean();
$resp = array(
'success' => true,
'data' => $data
); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "php, get template part"
} |
How to add custom text in wordpress logs
I am developing a custom code in wordpress and in order to debug that I need to know if I can add custom text in wpdebug log Please help me if i can do it | Hello Please add following code snippet in your theme's functions.php file
if (!function_exists('write_log')) {
function write_log ( $log ) {
if ( true === WP_DEBUG ) {
if ( is_array( $log ) || is_object( $log ) ) {
error_log( print_r( $log, true ) );
} else {
error_log( $log );
}
}
}
}
Now you can add custom log as and when you wish by using following output
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
write_log($your_variable);
Do let me know if you have any queries. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "plugin development"
} |
trying to get product category image in woo-coomerce
I am trying to get product category image.I ma using category image lugin for get category. < But problem is that when I am trying to fetch category image then showing null. I am using this code for getting category image
<?php if (function_exists('z_taxonomy_image')) z_taxonomy_image(); ?> | $prod_categories = get_terms( 'product_cat', array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true
));
foreach( $prod_categories as $prod_cat ) :
$cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
$shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, 'shop_catalog' );
$term_link = get_term_link( $prod_cat, 'product_cat' );?>
<a href="<?php echo $term_link; ?>"><img src="<?php echo $shop_catalog_img[0]; ?>" alt="<?php echo $prod_cat->name; ?>" /></a>
<?php endforeach; wp_reset_query(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, woocommerce offtopic"
} |
How do i send mail with custom Form Data using WordPress
I have a custom HTML form with input types and checkboxes. When I submit this form I want to send a mail will all the form details from the same php. How do I send the email from WordPress? I am pretty new and would thank for ur help. | `wp_mail` is the function you are looking for.
You can take the posted form data (`$_POST['email']`, for example) and then use it to build and execute the `wp_mail` function. The example below was taken from <
$to = $_POST['email']; //[email protected]
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
Also the above script would need to check for malicious attacks or bad input from the user but the `wp_mail` function will allow you to send email.
Source: < | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "email"
} |
Removing Extra Caption tag around image on post of WordPress
I am facing an issue when i use get_the_content() function. It displays the post content but the image in beginning of the content has some extra text around. My code is:
<div class="thecontent" itemprop="articleBody">
<?php echo get_the_content(); ?>
</div>
Output:
;
echo apply_filters('the_content', $content);
?>
</div>
But in this case picture isn't showing at all.
Output:
;
echo do_shortcode($content); ?>
</div>
The difference is, echoing just literally echoes whatever has been grabbed. PHP's built-in functions don't have any special way to process shortcodes so they just output as they've been told. By using a WP-specific function, WordPress parses whatever the content is and displays it. This works even if you have no shortcodes in the content. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, post content"
} |
Order posts by meta value hiding posts instead of re-ordering
The code below is suppose to display all posts with "featured_listing" meta key above all of the standard posts.
When the below code is in the functions.php, it hides all posts without "featured_listing" meta. Instead of showing them below the featured listings.
function custom_special_sort( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// if is this the main query and is this post type of business
if ( (is_post_type_archive('business') ) || (is_tax ('location') ) ) {
// order results by the meta_key 'featured_listing'
$query->set( 'meta_key', 'featured_listing' );
$query->set( 'orderby', 'featured_listing' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'custom_special_sort' ); | Literally seconds after updating this post I found the solution....again, Must have looked at this previously and not entered the details correctly as I tried this one before. :)
add_action('pre_get_posts', 'add_special_sort', 11, 1);
function add_special_sort($query){
// Bail if not the main "hidden" query, as opposed to a 'new WP_Query()' call
if(!$query->is_main_query())
return;
$query->set('meta_query', array(
'relation' => 'OR',
array(
'key' => 'featured_listing',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'featured_listing',
'compare' => 'EXISTS',
)
));
//$query->set('meta_key', NULL);
$query->set('orderby', array('meta_value_num' => 'DESC', 'date' => 'DESC'));
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, post meta"
} |
Select through customizer the template part to be viewed
I plan to make one-page website in which any section of the page can be chosen by the Admin to be displayed or not. I've seen in some themes that it is possible to turn off some template parts to hide different sections in the output page and it always seemed too cluttered to understand it. I am not interested in just hiding them, because proper theme_mod would be enough. I would like to affect the rendering of the section at all (so it doesn't even appear in the page source). I wonder then how, by using the Customizer e.g. checkbox, could I access the get_template_part() function. | Simply wrap the call to `get_template_part()` with a conditional that checks the value of the theme mod. If it were a checkbox it would look like this:
if ( get_theme_mod( 'my_checkbox_field' ) == '1' ) {
get_template_part( 'path/to/template' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, get template part"
} |
Display the 2nd category name of a custom post type without error if its null?
I have list items. These are custom posts.
* Post A belongs to category green and blue
* Post B belongs to category blue
* Post C belongs to category green and blue
* Post D belongs to category green and red
* Post E belongs to category green and blue
* Post F belongs to category blue
* Post G belongs to category blue and yellow
I want to loop each post and display second category name only of the post if there is one. If theres is not display the first category name as default.
So A should display category blue
B should be blue
C should be blue
D should be red
E should be blue
F should be blue
G should be yellow
Please help me achieve this using php. I beleive get_post _terms() is what needed here but I struggle to do it. Thanks in advance. | Inside of your loop you can get the terms via `wp_get_post_terms` function. Then, check if two or more terms exist. If they do, then use the function `array_slice` to extract the second term that appears in the array:
$term_list = wp_get_post_terms( $post->ID, 'YOUR_TAXONOMY', array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all') );
$display_term = (count($term_list) > 1) ? array_slice($array, 1, 1) : $term_list;
However, this does not determine how the terms will output from the database. You may want to define the `orderby` parameter to be something specific so you can predict which term will appear second.
Sources:
* <
* < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, customization"
} |
Large Session Tokens
We have a Wordpress site on a shared server that recently crashed due to running out of disk space, because our MySQL binary logs filled up the drive in a matter of minutes. After reviewing what was in them, we traced it down to a single user in this site that has ~3.4MB being stored in the `usermeta` table with a meta key of `session_tokens`. I clicked the Log Out Everywhere option for this user which deleted those records, but then today the same issue started occurring and all of his tokens are back.
Any ideas? I'm not really sure where to begin with this and have no idea how he's amassed this many tokens. I wrote a Wordpress scheduled task that is supposed to delete expired tickets hourly, but since his account had nothing and now today has thousands of them again, the expiration stuff must not apply. I took a peek at some of the expiration timestamps and they are all milliseconds apart, which confirms the scheduled task probably won't help. | No idea what happened, but the end user was having issues with his computer and somehow it was hanging on to those cookies. Since they weren't expired, nothing we did to remove them did a lot of good but getting the end user to clear cookies/cache resolved the issue.
I'd love to know more about the internals of how Wordpress handles this, but for now at least the issue is gone! I don't think there's anything we could've done inside Wordpress to prevent this though. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "security, session"
} |
ACF datepicker meta_query Compare Dates in m/d/Y g:i a - Not in Ymd Format
I'm looking for a way to use meta_query to filter out posts with a meta-key value of a date-time in `m/d/Y g:i a` format.
The post-meta is being set by ACF (Advanced Custom Fields).
I want to maintain `m/d/Y g:i a` formatting for output on the frontend, but also need to filter out posts with dates in the past.
I know that I can use `Ymd` format, likeso:
$date_now = date('Y/m/d');
$args = [
'meta_query'=>[
'relation'=>'AND',
[
'key'=>'event_time',
'value'=>$date_now,
'compare'=>'>=',
'type'=>'DATE',
],
]
];
I also know that I can retrieve all posts and use a subsequent loop to discard the posts which don't meet requirements.
But is there a better way to do this? Thanks for reading. | There should not be any need to do this.
Even if an ACF Field is using `'return_format' => 'm/d/Y g:i a',`
The post_meta value is in `YYYY-MM-DD 00:00:00` format.
$date_now = date('Y-m-d');
$args = [
'meta_key'=>'the_date',
'meta_value'=>$date_now.' 00:00:00',
'meta_compare'=>'>=',
];
$query = new WP_Query( $args );
**_Edit:** I've noticed some discrepancies in this, the value may be in `Ymd`. When in doubt, check the data. You can find the post_meta by looking up the `post_id` in the `wp_postmeta` table._ | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "wp query, advanced custom fields, meta query, date time"
} |
get_userdata by username
I am currently working with the REST API and have the need to `get_userdata()` but instead of the `user_id` I have the `username` I also have their email if that helps.
**Question:** Is this possible within the core functionality of WordPress? If not is there a round about way to get user info via username and then get the user_id from that to do the get_userdata call? | `get_userdata()` function is an alias of `get_user_by('ID')` function. Use this code:
$username = 'your user name';
$user = get_user_by('login', $username);
It will return WP_User object on success, or false on failure. See Codex.
**REST API** : ` | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 2,
"tags": "users, api, rest api"
} |
Using Blog Parent Slug on Blog Posts Only
_(Advanced warning: novice question)_
I'm trying to find a way to add a blog slug to any blogs I post. Example:
mysite.com/theblog/aparticualrblogpost
mysite.com/theblog/anotherblogpost
Any page created that isn't a blog should use the standard structure: mysite.com/agenericpage mysite.com/parentpage/anothergenericchildpage
How can this be achieved? | Just set your custom permalink structure to:
/theblog/%postname%/
If you have any custom post types used on your site, you’ll need to make sure that they don’t get the /theblog/ prepended to their URLs. To remove it, simply set with_front to false where the custom post types are registered:
'rewrite' => array('slug' => 'portfolio', 'with_front' => false),
You also need to flush the WordPress rewrite rules after making this change – just go back to Settings > Permalinks save again the permalink.
You are done. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "url rewriting, slug"
} |
Update Modified date when scheduled posts get published
I have a post scheduled to go out 1 week from now. I made the change today to schedule it and let it be.
When it finally gets published, the post date is the date it was scheduled to be published. But the modified date is still 1 week earlier!
How do I make it so that as soon as a scheduled post gets published it updates the modified date to the post date? | With the help of someone else, I managed to figure this out.
Add this to your functions.php:
// Scheduled posts should update modified date when published
function update_modified_date_to_post_date( $post ) {
$updated_data = [
'ID' => $post->ID,
'post_modified' => $post->post_date,
'post_modified_gmt' => $post->post_date_gmt
];
wp_update_post( $updated_data );
}
add_action( 'future_to_publish', 'update_modified_date_to_post_date', 10, 1 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, scheduled posts"
} |
Navigation Menus Depth for specific menus
I know that's possible to limit the depth that navigation menu items can be given children like this:
wp_add_inline_script('nav-menu', 'wpNavMenu.options.globalMaxDepth = 1;', 'after');
My issue is that I have three menus, and I only want to limit the depth on two of them. Is it possible to conditionally add the above when particular menus are being administered?
Limiting the depth displayed when actually rendering the menus in my theme is a last resort. I'd rather have the menu created in admin match the menu actually shown. | to know which menu is selected, you can do that in JavaScript
var selected_menu_id = $("#select-menu-to-edit option:selected").prop("value");
if ("56" === selected_menu_id) {
wpNavMenu.options.globalMaxDepth = 2;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, wp admin, navigation"
} |
Pull through featured image in a custom menu
Trying to pull through the featured image in a custom menu without a plugin so I can style it how I want.
This is the code I have so far;
<?php
$navMenu = wp_get_nav_menu_items(6); /*/Pass Nav Menu_id or Name*/
$previousMenuParent = $level = 0;
foreach ($navMenu as $menu) {
$level = 0;
echo '<li style="background-image:url("");"><a href="'. $menu->url .'">'. $menu->title .'</a>';
echo '<br><br>';
echo $menu->title = has_post_thumbnail($menu->object_id) ? get_the_post_thumbnail($menu->object_id, 'thumbnail') : $menu->title;
}
?>
I've also tried;
echo get_the_post_thumbnail($menu->ID);
I feel I'm so close but either get errors or nothing (or in the latest case just the title again)
Can anyone help get me over the line please? | <?php
$navMenu = wp_get_nav_menu_items(6);
foreach ($navMenu as $menu) {
echo '<li style="background-image:url( '. get_the_post_thumbnail_url( $menu->object_id ) .' )">';
echo '<a href="'. $menu->url .'">'. $menu->title .'</a>';
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails"
} |
Dynamic background image used in css after selector
.about-img:after {
background-image: url(../img/tola.jpeg);
}
How to dynamic above code in WordPress? It's not only background image but used in css after selector. | There is a way to do it. Just include that CSS inside header before wp_head() with internal css. And then add the Source using PHP like below
<style>
.about-img:after {
background-image: url(<?php bloginfo('template_directory')?>/img/tola.jpeg);
}
</style> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "custom field, metabox, meta query"
} |
Display specific Taxonomy Term from Custom Post Type
I have looked at multiple posts, but no luck. I need to use the loop how I have it for existing purposes, but I cannot figure out for the life of me how to return the terms of a custom taxonomy within a custom post type. Here is my code:
<?php $loop = new WP_Query(
'post_type' => 'dealmaker_pt',
'taxonomy' => 'topics',
'field' => 'slug',
'terms' => 'dealoftheweek',
'posts_per_page' => 50,
'offset' => 1 )
);
while ( $loop->have_posts() ) : $loop->the_post();
?>
stuffs here
<?php endwhile; wp_reset_query(); ?>
My post type is `dealmaker_pt` and my taxonomy is `topics` and I'm trying to display the specific taxonomy term of `dealoftheweek`.
How can I go about doing this? | Please use valid format for this Taxonomy Parameters
Example:
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'topics',
'field' => 'slug',
'terms' => 'dealoftheweek',
),
),
'post_type' => 'dealmaker_pt',
'posts_per_page' => 50,
'offset' => 1
);
$query = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "customization, taxonomy"
} |
Change text of twentyseventeen_edit_link()
Where do we go, or what do we do in order to change the default text displayed as `Edit` for the given function `twentyseventeen_edit_link()` which is originally part of the tweentyseveteen theme.
Thanks | The `twentyseventeen_edit_link()` function returns an accessibility-friendly link to edit a post or page. Here is its content:
function twentyseventeen_edit_link() {
$link = edit_post_link(
sprintf(
/* translators: %s: Name of current post */
__( 'Edit<span class="screen-reader-text"> "%s"</span>', 'twentyseventeen' ),
get_the_title()
),
'<span class="edit-link">',
'</span>'
);
return $link;
}
Since it doesn't provide a hook or filter, you have to use PoEdit to translate Twenty Seventeen's translation files. Everything you need is included in the PoEdit official site. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "theme development, translation"
} |
Is it possible to set default values for custom fields in a custom post type while my plugin is being activated?
I have been developing a plugin that creates a custom post type. The custom post type has many custom fields and I want to set default some values for these custom fields on activation.
How can I do this?
<li>
<label for="cx_number" class="sinop">Post Limit</label>
<input style="width:50px;" type="number" name="cx_number" id="cx_number" value="<?php if( !empty ( $postData['cx_number']) ) echo $postData['cx_number'][0]; ?>"/>
if ( isset( $_POST[ 'cx_number' ] ) ) {
update_post_meta( $post_id, 'cx_number', $_POST[ 'cx_number' ] ) ;
} | you can do that on a `save_post_` hook
try that :
add_action("save_post_" . CUSTOM_POST_TYPE, function ($post_ID, \WP_Post $post, $update) {
if (!$update) {
update_post_meta($post->ID, "cx_number", "default value");
return;
}
if (isset($_POST["cx_number"])) {
update_post_meta($post->ID, "cx_number", $_POST["cx_number"]);
}
}, 10, 3); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "customization"
} |
Remove admin menu links for multiple users by email
I've got 3 admin users and would like to modify admin menu for 2 of them by their email address, not by role (since the capabilities are all the same).
This works with a single email address:
add_action('admin_menu', 'remove_admin_menu_links');
function remove_admin_menu_links(){
$user = wp_get_current_user();
if( $user && isset($user->user_email) && '[email protected]' == $user->user_email ) {
remove_menu_page('tools.php');
remove_menu_page('themes.php');
remove_menu_page('options-general.php');
remove_menu_page('plugins.php');
}
}
What's the proper syntax for listing an array of email addresses?
I've tried the option below. It does nothing at all, stops working but no error either.
`if( $user && isset($user->user_email) && (in__array('[email protected]','[email protected]')) == $user->user_email ) { ` | Correct usage:
$arr = array('[email protected]','[email protected]');
in_array($user->user_email, $arr) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "users, array"
} |
When redirecting all URLs to homepage, what exceptions do I need to make?
I have a WordPress install that runs a few plugins purely as a backend. I want to completely hide the front end and just redirect it to the homepage. Should I redirect everything in htaccess and if so what exceptions should I allow? I assume there is a cron URL that should remain available? | The better solution was to create a new theme with the basic files required for a theme, in the main PHP file just add a PHP redirect to the root domain. This ensures anything front end related goes to to the homepage, everything else stays the same.
For WooCommerce you have to put a redirect in a header.php file too. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, wp cron"
} |
Tageting a specific menu link with nav_menu_css_class
The following is my `top-menu` when rendered on page...
<ul id="top-menu" class="menu">
...
<li id="menu-item-28" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-28"><a href="
<li id="menu-item-39" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-39"><a href=" Us</a></li>
</ul>
...what should my `if($item)` condition be to concatenate `my_custom_class` to `.menu-item-39`?
add_filter('nav_menu_css_class' , 'my_nav_special_class' , 10 , 2);
function my_nav_special_class($classes, $item){
if($item){ //what should this condition be?
$classes[] = 'my_custom_class';
}
return $classes;
}
Or should I be going about a better filter to process this same request? | An easier way to go about this: in menu administration, add your custom class directly to the menu item. To enable this, go to Screen Options at the top of the menu editing screen and check the "CSS Classes" box under "Show advanced menu properties."
Once you check that box, you'll have a new "CSS Classes (optional)" text input box for each menu item, and you can add it there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
How to replace default icon on "Add Media" button?
I want to use a different icon for Add Media button in the standard post editing form. What's the best way of doing it? | CSS is the way to go here.
Add a new CSS for admin using the `admin_enqueue_scripts` hook in your child theme functions.php (if you don't have one, you're doing something wrong)
function my_admin_enqueue_style() {
wp_enqueue_style('my-css', get_stylesheet_directory_uri().'/css/my-admin.css', array(), '1.0.0');
}
add_action('admin_enqueue_scripts', 'my_admin_enqueue_style');
In your my-admin.css file
/* change the content to another Dashicon */
#wp-content-editor-tools .wp-media-buttons .add_media span.wp-media-buttons-icon::before {
content: "\f104";
}
/* or set a background-image instead (set content to "" in the rule before) */
#wp-content-editor-tools .wp-media-buttons .add_media span.wp-media-buttons-icon {
background-image: url(../../wp-content/uploads/2017/10/my-image.png);
background-position: center;
}
Available Dashicon icons here | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "post editor"
} |
wordpress how to replace url /bar with foo/bar for custom post type
In my wp site there is a custom post type movies.i used cpt plugin to create it. so if i have a post with title `zootopia` it's url appear as ,
`
however i want to change this url to
` when i click view post i want this url to appear in address bar
so i want to replace url `/movie/` to `/parent/movie/`
i tried with `add_rewrite_rule` function
add_action('init', 'add_actor_url');
function add_actor_url()
{
add_rewrite_rule( '^movie/([^/]*)', 'parent/movie/$matches[1]', 'top' );
flush_rewrite_rules();
}
but this doesn't work.it doesn't replace url ` to `
is it really possible.if it's not then is there any other way to do that ? | You just need to set the slug to literally `parent/movie`. If you're doing it in code you set the `'rewrite' => 'slug'` argument to `'parent/movie'`. If it's in a plugin it would depend on the plugin, but there should be a setting for "slug" or similar. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, url rewriting, slug, rewrite rules"
} |
I only want to Display Author Link in authors bio
`the_author_link()` displays author name with hyperlink. I only want authors link to display and not authors name with hyperlink. how i suppose to do that?. thanks | You may consider using this function :
get_the_author_meta('url')
You can see here the implementation of the function `get_the_author_link()` and you will see how they construct the link with name. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "author"
} |
Performance impact of using global $post
I have two functions that do the same action: they add a title prefix for _expired_ posts. Which of these functions will affect more the site performance?
function expired_facebook_events_title_prefix_( $title, $id = null ) {
if( is_singular( 'facebook_events' ) && 'expired' == get_post_status() && in_the_loop() ) {
return '[expirat] ' . $title;
}
return $title;
}
add_filter('the_title', 'expired_facebook_events_title_prefix_', 10, 2);
function expired_facebook_events_title_prefix( $title ) {
global $post;
if( $post->post_type == 'facebook_events' && $post->post_status == 'expired' && in_the_loop() ){
return '[expirat] ' . $title;
}
return $title;
}
add_filter( 'the_title', 'expired_facebook_events_title_prefix' ); | There is no significant difference. Both will use a cached version of the current $post, in one you will access it via global $post, in other via functions that will get the data from the $post in the cache. I would suggest moving the in_the_loop() condition to be first in the IF. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "performance"
} |
Adding a title prefix with the the_title filter
I adapted an existing solution to add a prefix to _expired_ posts titles. It works, but it adds the prefix also to the main menu elements and to the Previous/Next links (that are not _expired_ yet). I removed the prefix from the menu elements by adding a supplementary `in_the_loop()` to the `if` condition, but this doesn't removed the prefix from the Previous/Next links. How to solve this?
function wpd_title_prefix_filter( $title, $post_id ) {
if( in_the_loop() && is_singular( 'facebook_events' ) && 'expired' == get_post_status() ){
$title = '<span class="expired-event">[expirat]</span> ' . $title;
}
return $title;
}
add_filter( 'the_title', 'wpd_title_prefix_filter', 10, 2 );
**UPDATE**
I solved it with CSS, but why this happens?
.nav-title .expired-event {
display: none;
} | This happens because **the_title** filter is run when the the_title() or related function is called to print the title, and prev/next links functions run the same the_title filter.
But, the problem here is that you are having general conditions that main post and prev/next fulfil: singular, expired post status and loop. To target the main post only in the single template add condition **$post_id == get_the_ID()** to your **IF** \- **$post_id** is the filter function argument, and **get_the_ID()** get's the ID of the global $post. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters"
} |
Redirect to homepage if attmpting to leave intranet
I have a client who wants a WordPress-based intranet, but does not want it to be a launching point for web browsing. I'm guessing there is a way to do this with javascript or with htaccess.
I get that simply opening a new window will probably work around whatever solution is applied to the site.
I also get that this is not strictly a WordPress question, but in the case of an htaccess solution, it may be. | Well, I'm not sure if this is the solution or not but the .HTACCESS might be useful. You can ensure only IP: xxx.xx.xx can view the site and then deny others.
IF this is helpful, place this in your htaccess file. You will of course want to update the ip address below to the access granted to said wordpress site.
Allow from 111.11.11.1
Deny from all | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, redirect, htaccess"
} |
How can i change an image's author?
Is there any function to change the image Author(Uploaded By) in WordPress library?

$my_post = array(
'ID' => $post_id,
'post_author' => $user_id,
);
wp_update_post( $my_post );
Or change image's author via a function using GravityForms uploader
add_action("gform_user_registered", "image_author", 10, 4);
function image_author($user_id, $config, $entry, $user_pass)
{
$post_id = $entry["post_id"];
$args = array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image'
);
$attachments = get_posts($args);
if($attachments) :
foreach ($attachments as $attachment) : setup_postdata($attachment);
$the_post = array();
$the_post['ID'] = $attachment->ID;
$the_post['post_author'] = $user_id;
wp_update_post( $the_post );
endforeach;
endif;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugins, php, functions, attachments"
} |
Translate text for empty product
I want to change the text of an empty product. But my code covers all products and I need this only for free products, meaning empty price products. Here is my code:
add_filter('gettext', 'translate_text');
add_filter('ngettext', 'translate_text');
function translate_text($translated) {
if( empty($product->price) ){
$translated = str_ireplace('Weiterlesen', 'Contact US', $translated);
return $translated;
}
}
This code is working perfectly, but it covers all products. I mean, the empty price condition is not working as expected here. | In your function 'translate_text' variable **$product** is not initialized, so the price is always empty. You need to provide the $product for use inside the function, consider the function, it should be global. Try modifying function:
function translate_text($translated) {
global $product;
if ($product && empty($product->price)){
$translated = str_ireplace('Weiterlesen', 'Contact US', $translated);
}
return $translated;
}
If your $product is set as global, this will work, if not, you need to set it like that, or think of another way to provide this function with outside variable. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins, php, woocommerce offtopic"
} |
Duplicate slug/permalink issue
I have a website which lists concerts and festival and some of them are returning each year. I have made a custom taxonomy where you can add the post to a year (2017, 2018, 2019 and so on). I also added the custom taxonomy to the slug (/shows/%archive%/%postname%/ – where archive is the year the post is in).
This works all like it should, URLs are now: /2017/name-of-show or /2018/name-of-festival
But when I re-add a festival for the next years edition I still get the URL with a -2 at the end, because of the post slug is already taken, while it should be /2017/festival-name and /2018/festival-name instead of /2018/festival-name-2
Am I missing something, or is this just not possible to do with duplicate names/slugs? | You can do that using Custom Permalinks Plugin, you need to add a full slug manually `[shows/2017/any]`.
It also allow you customize your permalink: `[anyname/another/2017/example/slug]`.
You should still using this plugin, if you deactivate it, all permalinks will return to _default_ `[shows/2017/%postname%]` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy, permalinks, slug"
} |
Multiple Domains and Subdomains Using Multisite Installation
I have the following domains/subdomains. They are all related to each other, yet they must be on different domains/subdomains
example.com
www.example.com (redirects to example.com)
sub1.example.com
sub2.example.com
example.net
www.example.net (redirects to example.net)
sub1.example.net
sub2.example.net
I would like to have a single WordPress installation for all the above (i.e., end up with a single DB). I do understand that I can setup a multisite installation if I have a single domain with subdomains. But for the above, this would mean I end up with TWO multisite installations (one for `example.com`, and another for `example.net`).
Is it possible to setup a single multisite installation with a single database allowing more than one main domain as shown above? If so, how?
Thanks. | Yes you can, I use 25 sub sites with different domains.
1- Point your domains to WP root folder.
2- Add a new site:
{
return "custom title";
}
add_filter('wp_title', 'customtitle', 10);
I'm also aware of the issues with changing custom titles and the yoast plugin. On the current WordPress setup I'm working with yoast is not installed. I wanted to know if there was another hook or method that I can override the title over the current default title. | This is most likely due to difference in your theme's support. Some themes render the title by using the `wp_title` filter, some by using `pre_get_document_title`. If your theme has this line in its `functions.php` file:
add_theme_support('title-tag');
Then you need to use the `pre_get_document_title` filter, as follows:
add_filter('pre_get_document_title', 'my_title');
function my_title() {
return 'Some title';
}
This is for the newer versions of WordPress. The old installations might be still using the legacy `wp_title()` function, which you already mentioned in your question. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "hooks, title, wp title"
} |
Remove "a href" from wp_list_comments()
My current theme comments are displayed using following code.
<ol class="comment-list">
<?php
wp_list_comments( array(
'style' => 'ol',
'short_ping' => true,
) );
?>
</ol>
I need to remove "a href" part.I mean their should not be linked to the comment author website.
I check `wp_list_comments()` from codex, but I could not find how to remove `<a href` part. | Deep down the function uses `get_comment_author_link()` to output the author name. That function is filterable. Inside the function it checks if the author has a URL and wraps the name in a link to it if it exists. We can use the `get_comment_author_link` filter to just output the name, and ignore the URL. This is pretty simple, since the callback for this filter gets the author name as one of its arguments, so we just need to pass it through untouched:
function wpse_284352_author_link( $author_link, $author ) {
return $author;
}
add_filter( 'get_comment_author_link', 'wpse_284352_author_link', 10, 2 );
**EDIT:** It's actually even simpler, the URL has its own filter, which means that can be filtered with one of WordPress' built in functions in one line:
add_filter( 'get_comment_author_url', '__return_empty_string' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "theme development, comments"
} |
How to link to img src using HTML email template in WordPress
I am using the Ultimate Member plugin on my website, to create user accounts. As part of this plugin, they allow you to customise the HTML email templates. I am trying to add an image as part of this email, using an image that I have uploaded using the WordPress media area.
To link to the image, I am using ''.
However, when the email comes through, the image is not there.
Can anyone suggest where I am going wrong please? | You are trying to link the image to a relative path `../wp-content/`. For the link to work in an e-mail, where the path isn't known to the reader, you must use the complete full path including ` or `
Like this: ` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, html"
} |
What are the downsides of using bootstrap in plugin development?
I want to use twitter-bootstrap in my plugin. Are there any downsides of that? Will it create any issue if other plugin are already using the same on WordPress environment? | Yes, there are clearly challenges to using such a public dependency as Bootstrap, especially in a public plugin:
* version conflicts;
* styling conflicts;
* script conflicts.
To minimize possibility of conflict and breakage you would need to consider following extra steps:
1. Importing _just_ the necessary Bootstrap styles into your stylesheet and making them specific to _only_ markup related to your plugin.
2. Only load JS scripts from Bootstrap that you need and putting them in `noConflict` mode, which will keep them out of global namespace and remap them so that only your plugin will make use of that specific instance. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins, plugin development, widgets, twitter bootstrap"
} |
Why does my WordPress show a 404 message for 403 forbidden directories?
I'm not sure if this is specific to my site or not, but if anyone knows how to override this behavior, that would be most appreciated! I have WordPress installed in the root directory of my server. There is also an unrelated sub-directory we'll call 'restricted-dir'. I have added an .htaccess file inside that directory with the following code:
Deny from all
Without that command, if a user visits www.my-domain.com/restricted-dir/ it would list all contents. I would like the user to receive the server's typical 403 Forbidden message, but instead WordPress kicks in and directs the user to my 404 page on my website.
Is there anything I can do to make the 403 page show up instead of the 404 page along with my entire WordPress install? | This question is old but in case anyone else comes across with the same problem, I found the answer in this ticket:
<
(For me solution #3 was the ticket, but I also have the first two in place so maybe it was a combination.) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "404 error"
} |
Is there a counter for comments left?
I'm looking for a way to have a counter of "left comments" per user for all readers of my blog. ¿Is this possible?
Cheers! | You can use `get_comments()` function to retrieve comments by `user_id` or you can modify the below to also accept `author_email` or multiple authors. It will then only return the Comment IDs as an array and count them up, returning the integer which could be 0.
/**
* Count and return number of comments by User ID
*
* @param Integer $user_id - User ID of the wanted user
*
* @return Integer - Number of comments by given user
*/
function wpse284435_comment_count_by_author( $user_id ) {
$user_id = ( ! empty( $user_id ) ) ? intval( $user_id ) : get_current_user_id();
$comments = get_comments( array(
'fields' => 'ids',
'user_id' => $user_id,
) );
return count( $comments );
}
$comment_count = wpse284435_comment_count_by_author( 7 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Unfamiliar HTML Properties in Avada and Divi Themes
I have looked at the DOM code for two WordPress themes that have tag properties that follow a pattern I have never seen before. These themes fit into the category of "framework themes", but I have not seen this use of properties in themes that stick closer to the WordPress codex. Here is an example: data-margin-right="0px" data-margin-left="0px" data-margin-top="31px" data-margin-bottom="31px"
When I do a Google search, it just picks up information about the default CSS rules: margin-left, margin-top, etc. I did figure out that CSS rules will override them, like it does other properties, within the normal specificity of CSS specifiers.
What is the story on these, ie. history, usage, constraints, etc? Should we look for this type of properties to show up in themes that more closely follow the WordPress codex. I have heard that WordPress is scheduled for a big technology change. | These are called data attributes, which are custom attributes in the format of `data-*` used to attach more info to the html elements.
This link here gives good examples on how to use them: <
Example:
<div id='el' data-my-attr='attr_value'></div>
**JavaScript** :
Most of the time, these info are used by JavaScript to fetch data and process them accordingly.
document.getElementById('el').dataset.myAttr; //Notice the property name uses CamelCase to replace the '-'s.
//Or using either of jQuery methods:
$('#el').data('myAttr');
$('#el').attr('data-my-attr);
**CSS** :
/* Use as selector */
div[data-my-attr='attr_value']{
/* styles */
}
And apparently you can also fetch its values using attr():
#el::before{
content: attr('data-my-attr');
}
So I guess one use for this is generating dynamic html and then set the CSS properties using the attr() in the CSS styles. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "html"
} |
403 error on admin login page
I've got a problem here. I have a wordpress site and accidentally changed the http to https and I am not sure that I could change it back. What is sure that it loged me out and when I reload the admin login page it throws an error that my connection is not private and after that I got a 403 Forbidden page.
I have access to the FTP and tried to change the wp_config file, no success. Tried adding this:
define('WP_HOME','
define('WP_SITEURL','
it only made the admin page reachable when I entered the user and pass it reloaded the login page.
I also tried to delete the .htaccess file, perhaps it is corrupted, but did not help.
Same question on stackoverflow. Please help me with this issue. | I managed to enter the admin page finally! So I added these two lines to wp_admin.php: ` define('WP_HOME',' define('WP_SITEURL',' ` afterward deleted the .htaccess file, then deleted browsing history, cleared cache and cookies. After all of this I could enter the admin page.
Then I went to options/general and options/permalinks and saved the setting, it generated a .htaccess file and now it is working.
I also tried removing the two added lines from wp_admin.php after all, but I broke the page so they are going to stay for a while. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "htaccess, errors, ssl, https, http"
} |
Select Tab name to show in browser's URL
I'm a front-end developer and currently working on a wordpress site. The site have a Tabbed section on one of the page, clicking on any tab load the relevant div (as expected). What I want is, when any Tab is clicked/selected, it's name should show up in the browser's URL bar. Please guide me in this, thanks.
* M. Jawaid | This is not something I would suggest and not sure why you want that. But using hashes you can do
$('#action_tab').click(function () {
window.location.hash = 'xyz';
return false;
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "urls, tabs"
} |
CSS reset for plugin’s front end?
Is there a best practice of implementing resets for front-end code? In back-end I can assume WP will handle reset itself, but I can’t be sure that front-end theme will have a reset (most likely it will).
How would one approach this? I don’t want to add a full reset for just one section, but I also don’t want to style for inconsistencies which should be done with reset. | In a plugin your styling should blend with the styling of the theme and not override it, therefor style "reset" is just not something you should do. On the contrary, it is better to have an option in your plugin to emit just HTML with no styling at all as it is hard to style anything in a way which will look good on all themes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Let Contributors Review only (Not Publish) Others Posts
I am currently developing a website which needs user input on posts. An admin will feed the data and regular visitors can notify the errors/additions to specific post. I am using a hidden login form which contains a contributor username and password to let the public login to the admin and make necessary changes. Its all working fine.
What I am looking for is, I don’t want the ‘Update’ button for the Contributor user when revising a post. Always keep it like ‘Submit for review’.
Any ideas? Thanks in advance! | When something is available for other people to read, it is usually called "published". This all thing sounds like an overly complex way to have posts which can be read by anyone (since the contributor user is basically public info) with a comment section.
I suggest you give some more thought about why do you want feedback to be private (nothing is perfect, and no matter how much feedback you get there there will always be more), but in case you truly think this is the way to go, than just publish the post as private and let people that are interested in reviewing it create a new user in a subscriber role, and leave their feedback as comments.
Having a public user with contributor credentials is a bad idea, giving him more capabilities than it has by default makes it even worse. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts"
} |
Admin meta Image Path
\inc\admin\inc\images
In the admin, images are kept in the above path. say: `image_1.png`
I have to call these images in the Wordpress Post admin in the " **Edit** " mode.
what is the correct method to include image source?
**I am trying to fix it like this →**
'img1' => '<img src="<?php echo get_template_directory_uri(); ?>/inc/admin/images/layout.png" alt="Image 1" title="Image 1">'
but not working | Unfortunately your question is still unclear after all the explanations, but based on your efforts, I guess you need to pass the image's URL to a meta field or some sort of array.
So, turning your current code into this will fix the issue:
'img1' => '<img src="'.get_template_directory_uri().'/inc/admin/images/layout.png" alt="Image 1" title="Image 1">' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, admin, metabox"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.