INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Accepted arguments value in hook functions
Let's say I have the following hook function:
function my_function() {
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
if( !isset( $_REQUEST['mode'] ) )
$_REQUEST['mode'] = ( $post_type == 'my_post_type' ) ? 'excerpt' : 'list';
}
`add_action( 'load-edit.php', 'my_function', 10, 1 );`
The fourth argument is (from WP Codex):
> (int) (optional) The number of arguments the hooked function accepts. In WordPress 1.5.1+, hooked functions can take extra arguments that are set when the matching do_action() or apply_filters() call is run. For example, the action comment_id_not_found will pass any functions that hook onto it the ID of the requested comment.
>
>
> Default: 1
>
The default value is 1, however I do not pass any arguments to the hook function.
Should I add an action like that?
`add_action( 'load-edit.php', 'my_function', 10, 0 );` | The accepted arguments value is used by WordPress as `$length` argument for `array_slice` when performing the action.
It means that, yes, if you pass `0` no argument will be passed to your callback.
However, you should care of that only if your function acts differently if an argument is passed or not.
A function like the one in OP, is defined without any argument, nor any function like `func_get_args()` or `func_get_arg()` is used in it, so it means that **you can pass any number of arguments to that function, but it will not change its behaviour**.
For that reason you can just ignore the 4th argument of `add_action` like so:
add_action( 'load-edit.php', 'my_function', 10 );
also consider that 10 is default priority, so previous line has same effect of
add_action( 'load-edit.php', 'my_function' );
It's not worse nor better from a code quality point of view, avoid to pass irrelevant arguments just saves you to type some chars. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, filters, hooks, actions"
} |
In post.php how can I remove onbeforeunload?
I am trying to remove the onbeforeunload on post.php but none of the solution I have found online work.
I tried:
(function() {window.onbeforeunload null;})();
I am using the action: admin_footer
I also tried to put it in the header.
I tried a few other things but to no avail.
On the post.php I removed the wysiwyg.
I am using WordPress version 4. | I just used this code:
$(".button").mousedown(function(){$(window).unbind();}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, javascript"
} |
Change Buddypress Admin Profile Page Permalink
Does anybody know how to change the default admin profile permalink in Buddypress which is: **domain.com/members/admin/** to this: **domain.com/members/MyUserName/**
I tried to change my name and it doesn't changes the permalink | This is a WP issue, not a BP issue.
User names cannot be changed via WP.
You could create another administrator account, using the user name you want, and then delete the 'admin' user.
Or you could use a database tool like phpmyadmin to access the users table. Find the row for 'admin' and change the name there. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, admin, users, buddypress"
} |
Adding a custom rewrite rule for gallery/categories page
I've written a simple shortcode and using it on my gallery page. The URL for the page looks something like this:
but I want to be able to use
When I use a URL like so, WP redirects to what seems the nearest match it can find. For example
redirects to
I've tried implementing a rewrite rule:
function add_custom_rewrites()
{
remove_filter('template_redirect', 'redirect_canonical');
add_rewrite_rule('^gallery/([^/]*)/?$', 'index.php/gallery/?category=$matches[1]', 'top');
add_rewrite_tag('%category%', '(.+)');
flush_rewrite_rules();
}
add_action('init', 'add_custom_rewrites');
but the /gallery/category page always redirects to try and by some means find the nearest matching page.
Can anyone help, please? | To answer my own question, I didn't need to remove the 'redirect_canonical' filter, and I only needed to change the 2nd parameter for add_rewrite_rule. The resulting function looks as follows:
function add_custom_rewrites()
{
add_rewrite_tag('%category%', '(.+)');
add_rewrite_rule('^gallery/([^/]*)/?$', 'index.php?pagename=gallery&category=$matches[1]', 'top');
flush_rewrite_rules();
}
add_action('init', 'add_custom_rewrites'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rewrite rules"
} |
How to check if the user registration is allowed/active?
I need to run a code snippet if the user registration is allowed, but I can't find a solution. How to do this? | You can check it very easily with the help of get_option.
Here is a simple code for checking if user registration is allowed.
if ( get_option( 'users_can_register' ) ) {
// Your custom code or message to display if user registration is allowed.
}
`get_option( 'users_can_register' )` returns boolean true (1) or false (0). | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 5,
"tags": "user registration"
} |
custom thumbnail image size not working
1. I added below code in theme's function.php
> add_theme_support( 'post-thumbnails' );
> add_image_size( 'thumb-small', 200, 150, true );
and `<?php the_post_thumbnail('thumb-small'); ?>` this in theme's file.
2. I tried this also in function.php
> function add_custom_sizes() {
> add_image_size( 'idea-thumb', 146, 141, true ); }
>
> add_action('after_setup_theme','add_custom_sizes');
`<?php the_post_thumbnail('idea-thumb'); ?>` this in theme's file.
3. `the_post_thumbnail( array(100, 100) );` // Other resolutions
But above three condition are not working.
`<?php the_post_thumbnail('thumbnail'); ?>` //this is working with 150 * 150px as default size.
what i had done mistake. | I Used **Regenerate Thumbnails** plugin to generate thumbnails | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails, images"
} |
how to make a new page affected by a theme's index.php layout?
I need to create some new pages for my website e.g. Gallery, Audio collection, etc. I want them to have a layout similar to my theme's index.php. How can I do this so that the layout updates for the mentioned pages if I change current theme for my WordPress website?
Do I have to use the same markup of index.php in new pages I want to create or is there a systematic way to tell WordPress to use the same layout for my theme's index.php for my new pages? | Wordpress loads templates in order from most specific to least specific, depending on which templates files exists.
For instance, lets say we have a wordpress page by name of "Audio Collection" with page ID of 14. WordPress would look for files by these names in order, and return the template for the first file name it checks that exists in your active theme.
* page-audio-collection.php
* page-14.php
* page.php
* index.php
So if you wanted to, you could create a duplicate of index.php, and call it page-audio-collection.php, and modify it as needed. That template would only be loaded when viewing the Audio Collection page, and all other pages would continue loading their current template file.
You could also create and assign a Custom Page Template, which would override all of the normal template hierarchy I outlined above.
read more at WordPress Template Hierarchy | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, pages"
} |
I want to rel=nofollow wordpress images
I have a default theme. When i add media to wordpress site. By default it use simple "a href" tag I want to add attribute "rel=nofollow" to it. Can anybody please point me in right direction?. | You need to hook into the image_send_to_editor filter. This allows you to modify the markup used when inserting an image into the content editor.
Something like this should work:
add_filter('image_send_to_editor', 'my_add_rel_nofollow', 10, 8);
function my_add_rel_nofollow($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
// check if there is already a rel value
if ( preg_match('/<a.*? rel=".*?">/', $html) ) {
$html = preg_replace('/(<a.*? rel=".*?)(".*?>)/', '$1 ' . 'nofollow' . '$2', $html);
} else {
$html = preg_replace('/(<a.*?)>/', '$1 rel="' . 'nofollow' . '" >', $html);
}
return $html;
}
This will first check if there is already a `rel` attribute, and add the no_follow. Or, if there is no `rel` attribute, it will add one, and set it to `nofollow`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, templates, page template"
} |
Get post thumbnail in WP_Query
I wrote an Ajax suggest plugin and I want to get the post thumbnail, but don't know how. This is my plugin code:
$s = trim( stripslashes( $_GET['q'] ) );
$query_args = apply_filters(
'wpss_search_query_args',
array(
's' => $s,
'post_status' => 'publish',
),
$s
);
$query = new WP_Query( $query_args );
if ( $query->posts ) {
$results = apply_filters(
'wpss_search_results',
wp_list_pluck( $query->posts, 'post_title' ),
$query
);
echo join( $results, "\n" );
} | Do you mean the featured image? Use `wp_get_attachment_image` \- Here is the code that I use in my plugin
while ( $the_query->have_posts() ) :$the_query->the_post();
$image_id = get_post_thumbnail_id();
$imagesize="thumbnail";
$image_url = wp_get_attachment_image_src($image_id, $imagesize, true);
//do something
endwhile;
You can also use `wp_get_attachment_url( $id );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, wp query"
} |
How to hide page links from theme menu
I'm working on a plugin, I programatically create some pages in posts table, the links appear in the theme menu(front end), I don't want some of these page links to appear, how do I do this? | Most of users use wp_nav_menu to output the menu in a theme, then you could make use of the callback function that is passed in the arguments array.
`wp_nav_menu( array( 'fallback_cb' => 'wp_page_menu' ) );`
`wp_page_menu` is the default value for the callback function.
Looking further, wp_page_menu has an `exclude` key in its arguments array.
`wp_page_menu( array( 'exclude' => '' ) );`
You can add a filter to it by adding comma separated values to the `exclude` key in the arguments array.
function my_cb_function( $args ) {
$args['exclude'] .= '10,20,30' // comma separated IDs
return $args;
}
add_filter( 'wp_page_menu_args', 'my_cb_function', 999, 1 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, menus"
} |
What's the purpose of index.php in wp-content directory?
<?php
// Silence is golden.
The folder is `../wp-content/index.php`
Why have this file. What's the purpose?
I suppose it's in order to avoid invalid visit.
But why? | Try to visit through the folder structure of your site from the browser:
You will see a blank page. That's actually is the `index.php`, and its content is very simple - a commented out PHP comment:
<?php
// Silence is golden.
Remove the file and visit the URL again. You will see the file structure completely. So your file structure is completely become naked.
That's why the file is there. To hide the inner file structure whatever that be.
O, don't forget to create the file again there. :) | stackexchange-wordpress | {
"answer_score": 25,
"question_score": 12,
"tags": "directory"
} |
Get info (url) from already enqueued styles
I am building a theme and using Easy google fonts WordPress Plugin. I created several typography controls within Theme Customizer for Post content,Post header, Author page content, Single Post content, 404 page content...
The plugin is loading all the fonts in any page I visit. I would like to hook the style enqueue of the fonts, and return only the necessary ones, so not every selected font is called in every page, just the necessary ones.
I know how to make use of wp_dequeue_script('tt-easy-google-fonts'); I am missing a way of returning the url of the already enqueued style. When I have it then I can dequeue the script, modify the url and enqueue my new version.
So my question is how can I get the url of the already enqueued styles/scripts? | Registered styles are in the `$wp_styles` global, and registered scripts are in `$wp_scripts`. You can `var_dump` them to see their structure.
global $wp_scripts;
echo $wp_scripts->registered['tt-easy-google-fonts']->src; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "plugins, theme development, wp enqueue script, wp enqueue style"
} |
What happens when you create/edit a menu
I need to know this for a plugin I'm developing: What happens when a user creates a menu, add/remove menu items in the admin, what updates are made in the database, what tables/columns are affected? | I just got into the database after trying this myself, so beware of inaccuracies. I'm also assuming the database-prefix is `wp_`.
What I found was that a refrence to the menu itself is stored in both `wp_terms`and `wp_term_taxonomy`. The one in `term_taxonomy`also stores the number of elements in the menu.
The relationships between menu items and posts are stored in `wp_term_relationships` as refrences to post_id's and taxonomy_id's. I hope this was somewhat helpful. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, menus, admin"
} |
Hiding menu on mobile only when viewing posts?
I would like to hide menu on mobile only when viewing posts. Menu at the homepage should be visible on mobile but not the other pages. How can I do it?
Here is the menu snippet:
<nav class="navigation cf" <?php echo implode(' ', $nav_data); ?>>
<div class="mobile" data-type="<?php echo Bunyad::options()->mobile_menu_type; ?>" data-search="<?php echo Bunyad::options()->mobile_nav_search; ?>">
<a href="#" class="selected">
<span class="text"><?php _e('Navigate', 'bunyad'); ?></span><span class="current"></span> <i class="hamburger fa fa-bars"></i>
</a>
</div>
<?php wp_nav_menu(array('theme_location' => 'main', 'fallback_cb' => '', 'walker' => 'Bunyad_Menu_Walker')); ?>
</nav> | Assuming you are editing a child theme (or somehow protecting your changes from future update/over-writing) a very simple way to accomplish this is with a CSS rule that targets your mobile menu, then applies `display: none` to it.
Using a combination of media queries and carefully written CSS selectors, you can target exactly the HTML elements you wish to hide, and in what context.
My guess is you will need a combination of body class (for the correct content type), media query and appropriate CSS. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, menus, mobile"
} |
Return child theme url
I'm trying to return the child theme url for a child theme favicon. The official code to use in this case is:
//* Display a custom favicon
add_filter( 'genesis_pre_load_favicon', 'sp_favicon_filter' );
function sp_favicon_filter( $favicon_url ) {
return '
}
but adding absolute urls stresses me out ;)
I know that
get_bloginfo('stylesheet_directory')
returns the correct url, so how do I get that into the 'return'?
I've tried
add_filter( 'genesis_pre_load_favicon', 'bg_favicon_filter' );
function bg_favicon_filter( $favicon_url ) {
$stylesheet_dir_uri = get_bloginfo('stylesheet_directory');
$stylesheet_uri = $stylesheet_dir_uri . "/images/favicon.ico";
return '$stylesheet_dir';
}
but I'm out my depth here
Any suggestions? | The correct function to use here is `get_stylesheet_directory_uri()`. Please feel free to read this useful post by @ChipBennet regarding this issue
Your use of syntax is also wrong in your return statement as already pointed out. A variable is php, not html, therefore you don't need the single quotes which are used to wrap html in a mixed string.
You can simply just use the following as your return statement
return get_stylesheet_directory_uri() . '/images/favicon.ico'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, child theme"
} |
Driving a random quote like functionality with database
I want to have functionality like this: A random quotes appears in particular section of the website (say sidebar) after a particular amount of time(say everyday).
I want to power it up using a new table in the database.
So maybe I will have these columns-
* Quote_Text
* Quote_Timestamp
* Quote_weblink (if any)
* Quoted_by
etc.
Can you help me get started on the code?
I know sql and can learn requisite php (I know other languages like java, c++ etc). But I don't have any experience with CSS (apart from some basic syntax). | I found a plugin and it used a custom database table which was what I was looking for. I will customize its code as the license allows to do so | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "posts"
} |
Issue with WP_Query (need a array of selected ID's)
Today I have
<?php $loop = new WP_Query( array( 'post_type' => 'inspirations', 'posts_per_page' => 50 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
which gives me all posts inside the tax `inspiration` \- I need to alter this, so that I get only selected ID's in my array, ex. 4714, 3608, instead of all terms of the tax.
According to WP Query arguments I need to alter the code to:
<?php $loop = new WP_Query( array( 'post_in' => array(4174, 3608), 'posts_per_page' => 50 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
But that does not return anything, not even a error.. What am I doing wrong here? :)
Thanks a lot for reading. | > which gives me all posts inside the tax inspiration - I need to alter this, so that I get only selected ID's in my array, ex. 4714, 3608, instead of all terms of the tax.
I'm assuming you mean that this query gives you all posts inside _post type_ inspiration and you want to pull specific post IDs instead of all _posts_ of the _post type_. Taxonomies and Post Types. are two different things.
Try to alter your query to something like this:
$loop = new WP_Query( array(
'post_type' => 'inspirations',
'post__in' => array( 4174, 3608 )
));
The difference between this and your original loop is that 1) There is a post type defined and 2) `post__in` has 2 underscore where yours has 1. I removed the `posts_per_page` parameter as this query should only return 2 posts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, loop, array, id"
} |
Cannot login to site after domain .COM address pointed at .ORG
We recently acquired the .ORG version of our domain. For migration, the IT staff pointed the .COM domain over to the .ORG address (e.g., < \--> --> < The WordPress site seems to be displaying HTML content fine, but no one can login. I cannot access the Dashboard as an admin. Password reset emails are not being sent, and attempts to reset the password via other means (< still does not allow login. Troubleshooting advice welcome. | Change the site address in your `wp-config.php` file:
define('WP_HOME','
define('WP_SITEURL','
There are other ways to do this too. See < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "domain"
} |
Using PHP to read Wordpress Posts
I'm a beginner in PHP and Wordpress and I would appreciate help on project I'm working on.
Currently I am using the below code to query a specific post and then echo it's expiration date (expiration date is set through a plugin) in a wordpress site:
<?php
$postid = 3823;
$date_format = __( 'd / m / Y' );
$expiration_date = get_post_meta( $postid, '_expiration_date', true);
echo date_i18n( $date_format, strtotime( $expiration_date ) );
?>
This is working fine. What I would like it to do is:
* I will have 2 posts, 1 published and one scheduled
* Query both posts, check which is publiched and echo it's expiration date | I think that you are looking for the function get_post_status Example:
if (get_post_status($postid)=='publish')
echo date_i18n( $date_format, strtotime( $expiration_date ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field"
} |
Remove rewrite endpoint on deactivation?
I'm using Milo's answer to add a Rewrite Endpoint as part of my plugin.
Is there a straight-forward way to remove a Rewrite Rule upon deactivation?
I found this snippet but I'd expect a "remove_rewrite_endpoint" to match add_rewrite_endpoint
Also, how do I know what to look for in the rewrite rules list when add_rewrite_endpoint was used to add the rule? | All you need is flush the rewrite rules on deactivation. For example, in the main plugin file:
register_deactivation_hook( __FILE__, function() {
flush_rewrite_rules();
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "rewrite rules"
} |
Wordpress Menu Exchange On Tablet's Orientation
I am using the plugin PHP Browser Detection and I want to achieve different menus for different devices. I have set them up called primary and mobile.
Now, I want to switch those on used device. Something like this I have done and it is working fine:
if ( is_tablet() ) {
wp_nav_menu( array('menu' => 'primary' ) );
}
elseif ( is_mobile() ) {
wp_nav_menu( array('menu' => 'mobile' ) );
}
else {
wp_nav_menu( array('menu' => 'primary' ) );
}
Now, I would like to go further, because the tablet's design looks nice in landscape view but bad in portrait mode.
So, I ask you, if there is a way to check the orientation (on tablets) and then go for it, meaning to change the menu from primary to mobile.
Something like that maybe:
if ( is_tablet(portrait) ) {
...
Thank you very much, guys. | cybmeta is right you cannot trust server-side browser detection
<div class="portrait">
wp_nav_menu( array('menu' => 'primary' ) );
</div>
<div class="mobile">
wp_nav_menu( array('menu' => 'mobile' ) );
</div>
<div class="primary">
wp_nav_menu( array('menu' => 'primary' ) );
</div>
and use media queries to hide and display menu | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, mobile, switch"
} |
Post Type Upload Directory - {post_type}_upload_dir filter
I'm working with modifying the upload directory depending on which post type is being uploaded to. I've ran across this question: Post type specific upload folder in 3.5 and one of the lines confused me:
`$uploads = apply_filters("{$type}_upload_directory", $type);`
Where `$type` is the post type. They then go on to join the paths:
$dir['path'] = path_join($dir['basedir'], $uploads);
$dir['url'] = path_join($dir['baseurl'], $uploads);
Which works fine, you get the expected upload folder of `wp-content/uploads/post-type-name` but what does the `apply_filtes` achieve? It seems like I could just change that line to:
`$uploads = $type` or `$dir['path'] = path_join($dir['basedir'], $type);`
and I will still get the same folder structure, so what does the `apply_fitlers` portion actually achieve? I can't seem to find reference on the filter anywhere either. | 'apply_filters' runs the value through all of the other hooks / functions attached to it. Try an experiment:
print_r( $type );
print_r( apply_filters("{$type}_upload_directory", $type) );
While you might, in your case, get the same thing - the apply_filters makes sure that any other plugins that try to influence this upload directory will still work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, media, uploads"
} |
Log out and redirect to different URL
I have a sign out on my site to log out of Wordpress
When logged out I would like to redirect uses to a different URL.
I'm using this in the functions.php
add_action(' wp_logout ',' auto_redirect_external_after_logout ');
function auto_redirect_external_after_logout(){
wp_redirect( ' ' );
exit();
}
and this in the header
<li class="signOut"><?php wp_logout(); ?></li>
When I run this I get a long list of errors in the page
Warning: Cannot modify header information - headers already sent by | To understand why your redirect isn't working, you should consider the mechanism it's using: the Location HTTP header. The problem here is that HTTP headers cannot be sent once you begin outputting content onto the page. Your task is to determine where that content is being output.
1. Is it a plugin? Try disabling all your plugins and see if that fixes it.
2. Is it your theme? Try switching to a different theme (modify it to use your logout hook) and see if that fixes it.
See also: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "redirect"
} |
Limit iframe output in comment-meta commentmetadata
Often people are posting Youtube videos directly into comment fields under posts, which is really a nice interaction and I have no problem with that.
My issue starts then, when I see those videos have the typical youtube iframe with over 400 px width.
Now, on a desktop website, there is no problem with that, but when you check that site on a mobile device, you see how the nice responsive theme you created just get messed up with those overlarge videos.
So I tried something like this in CSS to reduce the videos width:
.comment-meta commentmetadata iframe {max-width: 600px;} (or width: 100%;)
That did not help. All the posted videos are still larger than the site/post.
Anyone knows an easy solution without to delete all the posted videos? | declaring `max-width: 100%;` works for me. it looks like the selector in your example code is incorrect. try: `.commentlist iframe { max-width: 100%; }` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, youtube"
} |
Hide button based on PHP result
This is what i am trying to achieve but i am not sure how:
* I would like to check if a specific post is published or not
* If it' not published, it should hide a specific button and show a different one in it's place
I think it's a combination of PHP and CSS but i'm not really sure where to start.
Thank you in advance for your help Charis | You can use `get_post_status(ID)` to check to see if the post is published. You'll need to pull the post ID (through WP Query/loop/etc)
if (get_post_status( $ID ) == "publish"){
#Show Published Button
} else {
#Show Not Published Button
}
Get Post Status in the Codex | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, css"
} |
Echo post count of CPT with current taxonomy
I have a CPT called 'Athlete' and a Taxonomy called 'School'.
Two sample terms have been added called 'term1' and 'term2'.
When a user views the archive for any of the 2 terms (taxonomy-school.php), I need to be able to echo the current post count of posts from within the Athlete CPT that contain the currently viewed taxonomy term.
So basically something like this:
<?php echo count_posts ('athlete', 'school', $currentTaxTerm); ?>
Is this possible, appreciate any pointers? | In your taxonomy archive template, just add the following:
At the top: `global $wp_query;`
Then to get the post count for the entire term:
`echo $wp_query->found_posts`
This will display all posts in the query, which in a taxonomy template will be all posts attached to a term.
WP Query Codex | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, taxonomy"
} |
How to redirect correctly a root domain to a subdomain in a subfolder?
The next `.htaccess` code redirects `example.com` (from _/public_html_ root folder) to the `subdomain1.example.com` (to _/public_html/subdomain1_ subdolder) and an old page _register_ to a new one at `subdomain1.example.com/enroll`. So far so good! But, I have also a subdomain `subdomain2.example.com` (in the _/public_html/subdomain2_ subfolder) that instead of his normal URL is redirected to the `subdomain1.example.com/subfolder2`, that not exists. Why this happens and how to avoid this?
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) com/$1 [R=301,L]
Redirect 301 /register com/enroll | This is the adopted answer, thanks to @anubhava:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteCond %{HTTP_HOST} !subdomain.example.com [NC]
RewriteRule ^(.*)$ [R=301,L,QSA]
</IfModule>
Sourse: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, htaccess"
} |
Theoretical limit of upload file size
I want to setup a CMS on WP, which should contain a page, allowing to upload and download big files. We are expecting to use an Apache-server running on Ubuntu.
Assuming to adjust values, such as _upload_max_filesize_ ,
* which parameter limit the maximum file size
* what is the maximum possible file size (GB?)
* Are there other CMS, which allow to upload bigger files? | The Memory Limit depends on WP_MEMORY_LIMIT set by Wp_config file .So u can change the limit To higher value but Everything Depends on your Server Specifications. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads"
} |
Restricting page access
I need to restrict access to a page in a wordpress site for everyone but registered users. I have looked at a couple of plugins, and although they work well, they don't quite fit my solution... The page I am trying to restrict is based on a page template that itself has some hard coded forms that will interact with a backend server. The plugins I have tried block the WP content, but I can still see the forms from the template.
I need:
1. show login and registration box in-line on the blocked page that I can style (not redirect to standard WP logon)
2. upon successful registration, then the page will show the content including the template content. I hope this is clear and that someone can help me with either a better plugin, or a code solution.
Thanks | You can generate output conditionally with trivial `is_user_logged_in()` check in template. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, content restriction"
} |
List of users with email and role
I'm looking to create a list of all the users on my wordpress site with their email and role.
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
echo '<span>' . esc_html( $user->user_email ) . '</span>';
echo '<span>' . esc_html( $user->roles ) . '</span>';
}
This function is sort of what I am looking for but the user role displays as an array. Any thoughts on an easier way to do this?
Thanks | That's the correct way to get what you need. Though I'm not sure why WordPress returns an array of roles since ( to my knowledge ) you can only have 1 role at a time. Roles being an array you can modify by just retrieving the role index 0:
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
echo '<span>' . esc_html( $user->user_email ) . '</span>';
echo '<span>' . esc_html( $user->roles[0] ) . '</span>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user roles, users"
} |
Post query missing an elseif statement
I have a custom post type query which currently successfully returns tbe posts requested in the order specified. I would like to add an 'elseif' statement if there are no posts but am having absolutely no luck with it.
Can somebody please help me with how I insert the else statement?
I appreciate any help you can provide.
<?php $posts = get_posts(array(
'post_type' => 'retail_units',
'orderby' => 'date',
'order' => 'ASC'
));
if( $posts ) { foreach( $posts as $post ) { setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink();?>">
<?php the_title(); ?>
</a>
</li>
<div style="clear:both;"></div>
<?php } wp_reset_postdata(); } ?> | The `else` in PHP goes at the end of the `if` statements closing bracket, look at the following:
if( 1 == 1 ) {
echo 'true!';
}
else {
echo 'false.';
}
So you code would look something like this:
<?php
$posts = get_posts(array(
'post_type' => 'retail_units',
'orderby' => 'date',
'order' => 'ASC'
));
if( ! empty( $posts ) ) {
foreach( $posts as $post ) { setup_postdata( $post );
?>
<li>
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
</li>
<div style="clear:both;"></div>
<?php
}
wp_reset_postdata();
} else {
?>
<li>No Posts Found.</li>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
How do I change the footer (Norma)
I'm a total novice and this is my first experience with wordpress. I have some basic knowledge of HTML but that's about it. I need to change the the address information that we have set up in the footer. The theme that is being used is "Norma". If additional info is needed, I'll be happy to provide it, just let me know!
Thanks | Usually theme provides an option under Appearance/Customize (or around it) to adjust L&F. Because this is a commercial theme I can´t install or test it. You should better ask to their support people. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "footer"
} |
background_image support multiple image size?
Does background_image support showing multiple image sizes like feature image? I can see multiple files were created when I uploaded a file. How do I use those images or does background_image not allow that to happen?
Something like `get_background_image('large')` [doesn't work] or something where I can insert the dimensions after the file name like the-url-to-the-image-1024x768.jpg. | Figured it out using `str_replace`.
First the location of the background image is stored in a string:
<?php $backimg = get_background_image(); ?>
Then perform a string and replace where the `.jpg` is removed at the end of the `$backimg` and is stored as `$bgraw`
<?php $bgraw = str_replace('.jpg','',$backimg);?>
It output as:
The .jpg is removed; from there you insert the file you want to use. For example, I have a custom image where the dimensions are 1280px wide by 450px height. The image is created as fileimage.jpg-1280x450.jpg.
To use that image, take the stored value of `$bgraw` and add `-1280x450.jpg` or whatever file you want to use instead.
<?php echo $bgraw . '-1280x450.jpg' ;?>
That outputs as:
| stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, multisite, custom background"
} |
How to make Wordpress using local CSS/Fonts/Scripts only
For people in remote places with a bad internet connection, working on Wordpress stuff becomes real horror, not to mention : expensive!
Switching to a simple theme with no external dependencies could be a quick solution but I'd be interested in something more elegant. Is there a simple possibility to force Wordpress to cache external resources and rewrite the URLS?
Possibly there are plugins doing that already. any idea is welcome! thanks | There is a plugin Airplane Mode that tweaks good chunk of network–related things core does.
I am not entirely sure which kinds of external resources you mean. If you import site and its media into local development installation then most of it will be local already. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "css, offline"
} |
Custom post type with new taxonomy
I have a CPT called "products" so in the menu on the left there is "products" and "add new", I want to have "product categories" within the menu too so that the user can add as many product categories as they like, and then when they "add new product" they can assign it to a product category.
Here is how I have registered my CPT:
register_post_type( 'products',
// CPT Options
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'product' )
),
'public' => true,
'has_archive' => true,
'taxonomies' => array( 'Product-categories' ),
'hierarchical' => true,
'rewrite' => array('slug' => 'products'),
)
);
How do I get a "product categories" taxonomy menu within "products" on the left please?
Thanks | $labels = array(
'name' => _x( 'Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Types','SkyDance' ),
'all_items' => __( 'All Category','SkyDance' ),
'parent_item' => __( 'Parent Category','SkyDance' ),
'parent_item_colon' => __( 'Parent Category:','SkyDance' ),
'edit_item' => __( 'Edit Categories','SkyDance' ),
'update_item' => __( 'Update Category','SkyDance' ),
'add_new_item' => __( 'Add New Category,'SkyDance' ),
'new_item_name' => __( 'New Category Name','SkyDance' ),
);
register_taxonomy('category-cpt',array('cpt'), array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'category-cpt' ),
)); | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
How-to stop wordpress from saving utf8 non-breaking space characters
Anyone have a tip on how to prevent Wordpress from saving utf8 space characters (= hex C2 A0) in DB by replacing with space \x20 ?
Is there a hook that can be used to do a replace before saving to tables?
Background: ` ` looks like any other "space" character to the eye in editors (Notepad, Notepad++, Wordpress etc.) but actually hides itself in 2-byte code (`\xc2\xa0`) if you view though a hex editor.
Problem: css word-wrap causes sentence not to wrap as they should as it knows it's a "non-breaking space".
User experience: When someone does copy+paste from another source (website, word document etc.) sometimes the original space is a ` ` and the user doesn't see or know this as they're not that tech focused as we are.
Anyone has an idea or proposal for solution here?
Thx | Both initial creation and updates for the posts pass through `wp_insert_post_data` (among other filters). You can modify `post_content` item in array passed to make the replacement you need, before it proceeds on to be saved in database.
**Update** Code pasted from comments
add_filter( 'wp_insert_post_data', 'rm_wp_insert_post_data', '99', 2 );
function rm_wp_insert_post_data ( $data , $postarr ) {
return str_replace("\xc2\xa0", " ", $data);
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "visual editor, post editor, html editor"
} |
Should I use language_attributes() or bloginfo("language") in html tag
I heard there is two ways to put the language attribute into the html tag.
The two ways are:
* `<html <?php language_attributes();?>>`
* and `<html lang="<?php bloginfo("language"); ?>">`
Is there a specific coding convention everyone uses or is it a case where its up to the programmer. The reason is because I want my wordpress theme to have proper code according to the coding conventions. | Use `language_attributes()`, it handles rtl and html or xhtml doctypes, and has a filter that users may want to hook in a child theme.
You can see how they differ in source:
1. `language_attributes()`
2. `get_bloginfo()` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "theme development"
} |
Problem with images when no dimension in the URL
I have a problem on my site that when I open an image's direct link it goes to 404 page.
Here:
> <
With the dimensions it opens perfectly fine
Here:
> < | There was problem in my `.htaccess` file, that was preventing direct image urls | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "images"
} |
How do I pull avatar from post using BuddyPress?
I'd like to pull the avatar of a blog post's author and display it on the page using BuddyPress but I cannot seem to pull it off. How would I go about this? | Try this:
$author_id = get_the_author_meta('ID');
echo bp_core_fetch_avatar ( array( 'item_id' => $author_id, 'type' => 'full' ) );
Defaults:
array(
'item_id' => false,
'object' => 'user',
'type' => 'thumb',
'avatar_dir' => false,
'width' => false,
'height' => false,
'class' => 'avatar',
'css_id' => false,
'alt' => '',
'email' => false,
'no_grav' => false,
'html' => true,
'title' => '',
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, buddypress, avatar"
} |
How to send language string in email message body
I am using wp_mail() function to sending email. I have one static string "Hello Admin". My clients wants convert this string to language string. So it possible to convert static string to language string while sending email.
What I have done so far, please refer my below code.
$current_user = wp_get_current_user();
$admin_email = get_option('admin_email');
$subject = get_bloginfo('name').' - Publish Details';
$message = _("Hello Admin,",'text-domain');
$message .= "$current_user->user_login has published details. Details are as following.\r\n";
wp_mail($admin_email,$subject,$message,$headers)
Output:
John has published details. Details are as following.
I am not getting language string in email. Any help would be appreciate. | You have a typo in your code, the function is `__()` with two underscores. You will also need to configure the textdomain 'text-domain' and have a valid translation for the end users' browser settings for it to not default to english.
// use two underscores in the method
$message = __("Hello Admin,",'text-domain');
// assuming this is a plugin and your language files are in a /languages subdirectory
function load_textdomain() {
load_plugin_textdomain( 'text-domain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action( 'plugins_loaded', 'load_textdomain' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp mail, language"
} |
Is it risky if I update all url in the database due to my site url changed?
Let's say I have a wordpress site on a subdomain.
Initially, I created the site with "www." >>> www.mysite.mainsite.com
Now, I'd like to change site url to only mysite.mainsite.com without www anymore.
I can change it via Settting > General but I checked the database and I found that all of my images in media library (guid field of the posts table) are still having www.mysite.mainsite.com with www which I don't want it anymore.
I also found this thread related to this Changing www prefix in General Settings and Interior Links
But anyone can suggest if it's risky to do that or not? Will the code there usable for today?
Thanks | I have updated the URLs stored in the database when the domain has changed.
Here are the things to watch for:
1. In the `posts` table, the post_content will have any embedded links. These you can change without issue.
2. Again in the `posts` table, the gid would change if you do a global search and replace. This is mostly used with regard to RSS feeds. You can either change them or leave them without much issue unless the RSS GID is important to you.
3. In the `postmeta` table, this is where it gets tricky. If the field is just a raw string field, then you'll have no issue changing it. **The issue is when the URL is within serialized PHP data.**
**Why serialized data would break**
When PHP serializes a string, it embeds the length of the string. For example, ` becomes `s:22:" Notice the `22` after `s:`, this is the string length. If we drop the `www`, then the serialized value would be: `s:18:" If the length is wrong, then the data becomes garbage to WordPress. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, site url, guids"
} |
Remove function or filter
Im working with a child-theme of Wordpress-Bootstrap by 320press.com I want to get rid of the lead class added to the first paragraph of the content.
I looked in Wordpress codex in these articles:
* `remove_action`
* `remove_filter`
But im not so experienced in PHP, only HTML - so i cant really tell if its a filter or a function that i need to remove - i tried both solutions in above links, but i cant seem to get any of them to work.
This is the PHP from functions.php that adds the class
// Add lead class to first paragraph
function first_paragraph( $content ){
global $post;
// if we're on the homepage, don't add the lead class to the first paragraph of text
if( is_page_template( 'page-homepage.php' ) )
return $content;
else
return preg_replace('/<p([^>]+)?>/', '<p$1 class="lead">', $content, 1);
}
add_filter( 'the_content', 'first_paragraph' ); | Your problem isn't that you did the wrong thing, it's that you did it at the wrong time. When it happens is important, not where.
In a child theme, the functions.php is loaded, then the parents, so you're doing this:
1. Remove the `first_paragraph` function from `the_content` filter
2. Add the `first_paragraph` function to `the_content` filter
Clearly this is the wrong way round. It's like building the penthouse of a skyscraper first then building the foundations second, it isn't going to work. Here you can't remove the filter because it hasn't been added yet
To get around this, remove the filter at a later point using an action/hook, e.g.:
// when the init hook fires
add_action( 'init', 'sillo_remove_that_filter' );
function sillo_remove_that_filter() {
// remove the filter
remove_filter( 'the_content', 'first_paragraph' );
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "functions, filters"
} |
Multiple instance of data in plugin custom database table on plugin activation
I'm creating a plugin that adds some data to a custom table created by my plugin on plugin activations.
I also created a settings page with a form that users can insert their own data to the database.
**The problem** Everything is working fine but each time i deactivate(i don't mean uninstall) and reactivate the plugin, the data get duplicated in the table.
Mind you, due to the large amount of data, i chose to use "longtext" as the table column type.
Making the columns type is not an UNIQUE.
**My question** How do i prevent the plugin from inserting the same data that was meant to be inserted int the database just once on plugin activation? | Found a great solution.
Basically, you can check if an option name exists and if it already exists you don't insert your data.
The main idea is, each time your database schema changes and requires an update on your user’s database, you need to increment the DB_VER by 1, then write a database upgrade routine for the current DB_VER. This would create some sort of an evolution trail of your database schema, which is very helpful when your user needs to upgrade from an ancient version to the latest one. WordPress itself keeps track of its schema changes this way, so it’s always safe to upgrade from WordPress 2.x to 3.x without much issue.
Full explanation on how this work ca be found at here < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, database, mysql, activation, table"
} |
Does WordPress support Plupload chunking when uploading asynchronously?
I'm using the Plupload library to upload audio files to my website from the front-end. Here is an example of my Plupload config:
var uploader = new plupload.Uploader({
browse_button : 'browse',
file_data_name : 'async-upload',
multipart_params: {
action : 'upload-attachment'
},
url : ajax_url,
flash_swf_url : flash_swf_url,
silverlight_xap_url : silverlight_xap_url,
chunk_size : '200kb',
max_retries : 3
});
My aim is to break files down into smaller 'chunks' whilst uploading. Plupload has built-in support for this.
**My question**
An example of server-side chuck handling is provided by Plupload. Does WordPress handle chunks server-side when uploading asynchronously or is this something I have to do myself?
Ref: < | To the best of my knowledge, no, the async-upload process on the WordPress side does not support chunking from plupload. You can find this code in /wp-admin/async-upload.php.
To handle the uploaded file, it calls the wp_ajax_upload_attachment() function, in the ajax-actions.php file. This function refers directly to the PHP $_FILES array, meaning that the file would be completely uploaded and saved to a tmp file by PHP before WordPress is invoked. Therefore chunking is not directly supported. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, library, plupload"
} |
moving tables between multisite installs
So I have a WP multisite install where our client made changes over on a staging site. But now we need to bring the changed tables back in. The issue is we didnt bring the entire DB to staging, and cant bring the entire DB back in. We have 260+ sites and only need to stage the one site and test a few sub sites. So our staging is like a cross section of 15 sites.
I know how to move sub sites with a clear ID (wp_#_) but this is blog ID #1.
So i brought in ALL non site specific wp_ tables but nothing.
So where is blog id #1 data saved if there is no wp_1_ in my 10k table DB? | So turns out the client had us working on the wrong database. One with all the same files, but not the one the site was pulling from. Ugh.
Yes, WP_ is the right set of tables to move and all is well when you are on the right DB. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite"
} |
Function to remove archive sidebar for custom taxonomy?
I have a custom taxonomy/custom post category and I'm trying to write a function, which removes the sidebar from the archive pages, only when there's a (custom) taxonomy match. The match part isn't the issue, but I'm unable to silence WP's `get_sidebar()` (triggered by `arhive.php`). The best result I got, removed not only the sidebar, but also the footer and admin header menu... which is a bit too much.
Does anyone know how to disable `arhive.php`'s `get_sidebar()` via `functions.php`? | Use custom archive template for your custom taxonomy. so if your taxonomy is 'XYZ' , its archive page will be taxonomy-XYZ.php. Now in this custom archive page for your custom taxonomy, you can choose to add /remove sidebar as per your requirement. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "customization, taxonomy, sidebar"
} |
Specify image dimensions
I ran a performance report for my website (using GTmetrix) and I realized the image dimensions are not set, and I missed specifying the height and width attributes. The theme already had some images, but they are not specified by default. How can I specify them and more importantly, where do I specify the attributes height and width?
<div class="thumb">
<a class="clip-link" data-id="1" title="Hello world!" href="
<span class="clip">
<img src=" alt="Hello world!" />
<span class="vertical-align"></span>
</span> | In your theme's functions.php file you can add
add_image_size( 'thumb', 600, 350, true );
add_image_size( 'thumbnil', 600, 350, true );
add_image_size( 'medium', 600, 350, true );
add_image_size( 'large', 600, 350, true );
add_image_size( 'post-thumbnail', 600, 350, true );
add_image_size( '{custom-image-type}', 600, 350, true );
For more information have a look at < | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "theme development, images"
} |
Does WPML translate numbers automatically, or do I have to do the string translation?
I'm developing my site in **English** , and when I'm done, I'll be turning it into Arabic. I'm using a function and wondering whether I should wrap it into a gettext call for WPML to get or just leave it as it is and it will be converted into **Arabic** automatically (since it's numbers and not text)?
Should I do this?
<?php echo $woocommerce->cart->cart_contents_count;?>
Or keep it like this?
<?php echo sprintf(__('%d', $woocommerce->cart->cart_contents_count));?>
Thanks! | It is better to use gettext calls, according to WPML Guidelines. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "translation, plugin wpml, xgettext"
} |
Can you pre-check wordpress categories?
I have created a custom taxonomy, which has 2 terms. I'd like to have both of these checked/selected by default when someone creates a new post. Is this possible? I've searched but found no solutions.
Thank you! | There is nothing directly meant for that (that I can think of), but there is very close in purpose function `get_default_post_to_edit()`.
Since for the purpose of new post creation it makes post appear in DB before it is even saved for the first time (as auto draft) we can tinker with its filters a bit to make it happen:
add_filter( 'default_content', function ( $content, $post ) {
if ( ! is_admin() ) {
return $content;
}
$screen = get_current_screen();
if ( 'post' === $screen->base && 'add' === $screen->action && 'code-project' === $screen->post_type ) {
wp_set_object_terms( $post->ID, 'plugin', 'code-project-type' );
}
return $content;
}, 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, custom taxonomy"
} |
Way to count the number of people who have commented on a post?
There doesn't seem to be an easy WP way to show the total number of different commenters, just total # of comments.
Is there a better than manually loop through all comments and counting the unique user ID's? | You could try to count the number of **unique** _comment author emails_ per post:
/**
* Number of unique comment author emails per post:
*
* @see
* @param int $pid
* @return int
*/
function get_unique_commenters_by_post_id( $post_id )
{
global $wpdb;
$sql = "SELECT COUNT(1) as uc FROM (
SELECT COUNT(1) as c FROM {$wpdb->comments}
WHERE comment_post_ID = %d
GROUP BY comment_author_email
) as t";
return $wpdb->get_var( $wpdb->prepare( $sql, $post_id ) );
}
**Usage example:**
echo get_unique_commenters_by_post_id( $post_id = 213 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments"
} |
Display URL in a Custom Field
I'm using the following code to display several custom fields on my posts in WordPress, but the URL field doesn't work as I want and I don't know how to solve it:
$destino_web = get_post_meta( get_the_ID(), 'web', true);
$destino_telefono = get_post_meta( get_the_ID(), 'telefono', true);
$destino_precio = get_post_meta( get_the_ID(), 'precio', true);
$destino_horario = get_post_meta( get_the_ID(), 'horario', true);
if( ! empty( $destino_web ) ) { echo '<p><strong>Web:</strong><a href="' . $web . '"><?php get_the_title(); ?></a></p>'; }
if( ! empty( $destino_telefono ) ) { echo '<p><strong>Telefono:</strong> ' . $destino_telefono . '</p>'; }
if( ! empty( $destino_precio ) ) { echo '<p><strong>Precio:</strong> ' . $destino_precio . '</p>'; }
if( ! empty( $destino_horario ) ) { echo '<p><strong>Horario:</strong> ' . $destino_horario . '</p>'; }
I would like to display the post title with my custom URL. | You are using get_the_title(), which needs to be echoed out. However, you have it inside the string. Also, you might want to use isset() rather than !empty().
Try this:
if( isset( $destino_web ) && $destino_web !== '') { echo sprintf('<p><strong>Web:</strong><a href="%s">%s</a></p>', $destino_web, get_the_title() ); } | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, urls"
} |
Extract post category except one category
My posts are in two categories - one that defines their type eg. `article` or `review` and the other defines the topic - `tablets`,`smartphones`,`smartwatches`, etc.
How can I get the current post's category ID for its topic - i.e. whether it's a `tablet`, `smartphone` or `smartwatch`.
If I do `get_the_category( $post->ID );` I suppose it'll return all categories the post is in, but how do I filter out the `article` or `review` categories out?
Example: Post `ABC` is in categories `article` with `ID=1` and `tablets` with `ID=10` how can I extract on the `tablets` `ID=10` category without the `article` one? | You can simply loop over the categories that you don't need. `get_the_category()` return an array of categories that the post belongs to.
With that in mind, you can do the following: ( _Just remember to change`21` and `41` to your desired ID's_)
$categories = get_the_category();
foreach ( $categories as $category ) {
if( 21 === $category->cat_ID || 41 === $category->cat_ID ) {
continue;
}else{
echo $category->cat_ID . '</br>';
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
WP_query problem -spurious results
What am I missing?
<?
//Specialities Query
$args = array(
'post_type' => 'page',
'post__in' => array(24, 26, 28),
) ;
$specialities_query = new WP_Query( $args );
// The Loop
while ( $specialities_query->have_posts() ) :
$specialities_query->the_post(); ?>
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Read more on %s', 'karenmann' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark" class="show"><?php the_title(); ?></a>
<? endwhile;
/* Restore original Post Data */
wp_reset_postdata(); ?>
returns 5 pages, id 7, 11 and then the three above 24,26,28. This query is in a sidebar and I normally manage these quite well I was originally using post_parent but also getting spurious results though slightly different to this and, at the end, including these three posts.
Site: development.karenmann.co.uk | Ids 7 & 11 are probably `sticky posts`.
Try this:
$args = array(
'post_type' => 'page',
'post__in' => array(24, 26, 28),
'ignore_sticky_posts' => 1
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
Upload & include specific JavaScript files for posts?
I need to include specific Javascript files on specific posts. This will be done in pretty much every post and each file is unlikely to be included in more than one post. I know I could just upload the files via FTP and put a `<script>` tag at the bottom of the post, but I would like to do it all from the dashboard.
So I want to create a custom field in post-new.php where I can upload javascript files to the database, then in single.php I add a line of code that includes the files at the bottom of the page.
What's the best way to achieve this? | Upload the file as media/attachment, add post meta data and add it as dependency to the footer via the Dependency API. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
Displaying posts on homepage - Template Page
I created two template pages: `galerie.php` and `homepage.php`.
Galerie already displays posts. So Homepage is `homepage.php` and posts page is `galerie.php`.
Now the problem is that I wanted to display a post from Category `category-test` into `homepage.php`. I used the following code to try to display the posts from `category-test`:
<?php $posts = get_posts('category_name=' . 'category-test'); foreach($posts as $post) { ?>
<?php the_title(); ?>
<p><?php the_content(); ?></p>
<?php } ?>
But for some reason this only displays the post title. It doesn't display the body content of the post.
What is the problem with it? | The template tags (like `the_content()`) aren't available when using `get_posts`. In order to make the template tags available, you have to make use of `setup_postdata( $post );`
Example:
<?php
$posts = get_posts('category_name=category-test');
foreach($posts as $post) {
setup_postdata( $post );
the_title(); ?>
<p><?php the_content(); ?></p>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, page template, homepage"
} |
If statement within PHP echo
I have the following to display my list of categories:
$categories = get_categories( $args );
foreach ( $categories as $category ) {
echo '<li><img src=""/><a href="' . get_category_link( $category->term_id ) . '" rel="bookmark">' . $category->name . '' . '' . $category->description . '</a></li>';
}
But I am using the "categories images" plugin to assign an image to each category (which is what the
> img src="" />
is for within the code. Within the src="" I need to get the following IF statement:
<?php if (function_exists('z_taxonomy_image_url')) echo z_taxonomy_image_url(); ?>
or even just the:
z_taxonomy_image_url();
How can I make this work please? | According to the plugins documentation (< this seems pretty simple:
<ul>
<?php
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$img_src = z_taxonomy_image_url($category->term_id);
if ( $img_src ) {
echo '<li><img src="' . $img_src . '" alt="" /><a href="' . get_category_link($category->term_id) . '" rel="bookmark">' . $category->name . ' - ' . $category->description . '</a></li>';
} else {
echo '<li><a href="' . get_category_link($category->term_id) . '" rel="bookmark">' . $category->name . ' - ' . $category->description . '</a></li>';
}
}
?>
</ul> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, custom taxonomy"
} |
ReOrder Post Within Categories plugin with featured image
I need to add featured image somewhere near title so I can easier sort them, currently the plugin use this code to show the title only, tried with the_post_thumbnail and nothing is showing up. Thank you.
echo '<li id="'.$post->ID.'">';
echo '<span class="title">'.$post->post_title.'</span>';
echo '</li>'; | Since this is a plugin, it's probably going to get axed, but generally speaking in WordPress if you want to get a posts featured image and you have access to the post ID (which I'm assuming you do), you can always do this:
$thumb_url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
So without looking at the plugin, it looks like you might be able to do something like this:
$thumb_url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
echo '<li id="' . $post->ID . '">';
echo '<img src="' . $thumb_url . '" alt="" />';
echo '<span class="title">' . $post->post_title . '</span>';
echo '</li>';
Set your styles on the image accordingly (height/width/float/margins/etc.) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, post thumbnails"
} |
Self-hosted Plugins & Themes store with auto-updates?
I'm looking for a way to self-host a WordPress Plugins/Themes store (ideally at no cost — I am but a poor developer!) with the following features:
* Sell Plugin/Theme downloads
* Auto-updates for sold extensions with WP Admin updater
* Managed with interface rather than pushing files
Nice-to-haves would be:
* Product gallery
* PayPal support
* License keys
* Managed inside WP Admin
Googling and searching SE has been unfruitful so if anyone knows a way to do the above please let me know! | The only free solution that I know of is WP Updater. However, this only handles automatic updates for plugins that are self-hosted. It does not handle any product sales or license keys. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "plugins, themes, updates, e commerce"
} |
Translating wordpress plugin
I built contact form plugin in in wordpress. I am planing to translate field name to diffrent languages. In that cause i will use Poedit. My question is does wordpress has some language options in database, wich could be used. For example when wp is installed you could choose diffrent lang options? So my question how i will trigger translation for my plugin? I read something about constant in wp-config, is there any way to trigger change of language without this constant, cuz i am having separate plugin | You get the current language of the install with the function `get_locale()`. WordPress save the language in the`options` table, `option_name` is `WPLANG`. But inside the Multisite install is in the table `sitemeta`.
But is not important. You should use the default functions to load a language file inside the theme template or the plugin.
* Theme: `load_theme_textdomain()`
* Plugin: `load_plugin_textdomain()`
You find a small example inside this contact form template, public. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
get_category_link returning page URL
I am using the following code to display a list of categories in a custom taxonomy, except the URL returns only the current page URL.
<?php $category_ids = get_all_category_ids(); ?>
<?php
$args = array(
'orderby' => 'slug',
'parent' => 0,
'taxonomy' => 'servicecats',
'hide_empty' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$imgurl = z_taxonomy_image_url($category->term_id);
echo '<li><img src="'. $imgurl . '"/><a href="' . get_category_link( $category->term_id ) . '" rel="bookmark">' . $category->name . '' . '' . $category->description . '</a></li>';
}
?>
I have read in other topics I should be using get_term_link but this gave me an error, also changed get_categories to get_terms and my categories disappeared off the screen. How can I get this URL to link to the category please? | I changed get_category_link to:
esc_attr(get_term_link($category, 'servicecats'))
Thanks to this site | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy"
} |
fetch_feed works on localhost but not on server
There is one similar question, but I can't seem to get round to what's going on. So any help appreciated...
The following code works just fine on localhost, but when on the live site I get the following: WP HTTP Error: connect() timed out!
<?php if (function_exists('fetch_feed')) { ?>
<?php include_once(ABSPATH . WPINC . '/feed.php');
$feed = fetch_feed('
if ( ! is_wp_error( $feed ) ) :
$limit = $feed->get_item_quantity(2);
$items = $feed->get_items(0,$limit);
endif;
if (!$items){
echo $feed->get_error_message();
} else {
foreach ($items as $item) { ?>
<h4><?php echo $item->get_date('F j, Y'); ?></h4>
<p><?php echo $item->get_title(); ?></p>
<?php }
} ?>
<?php } ?>
Thanks! | At first check or set the timeout window on the online install, keyword `max_execution_time`.
Also a hint to the feed, there have a issue, often also a problem for the connection: <
Also a chance is a plugin or function inside the Theme, that cut the connection.
The last point, that you should check this two constants. Ther should be on `true` value for connections.
* `WP_HTTP_BLOCK_EXTERNAL`
* `WP_ACCESSIBLE_HOSTS`
More background about WordPress and Offline Topic can you find in this source of the plugin. But you must check the contrary ;) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "rss, feed"
} |
Set the background to a default image if there isn't a specified "featured image"
I am having a little trouble displaying a default image as a background image when a feature image is not present. This is the code I am using
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );?>
<?php else :
$src = get_bloginfo( 'stylesheet_directory') . '/lib/images/home1-1024x681.jpg'; ?>
<?php endif; ?>
<section id="halfpro" style="background:url(<?php echo $src[0]; ?> ) no-repeat center center">
When I upload a feature image it works but when I do not have one selected the div is empty. When I look at the source it seems as though it is not rendering the URL correctly, I am getting this background:url(h ).
What am I missing? | I found the solution from a Wordpress forum and this is what they used. Works perfect
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), '' );
$image = $image[0]; ?>
<?php else :
$image = get_bloginfo('stylesheet_directory') . '/lib/images/home1-1024x681.jpg'; ?>
<?php endif; ?>
<section id="halfpro" style="background-image: url('<?php echo $image; ?>')" > | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, functions, post thumbnails, images"
} |
Translating wordpress plugin
Ok i built plugin for contact form, I wanna add translation for it. In my main plugin files i add this code
function ap_action_init()
{
// Localization
load_plugin_textdomain('prijava_forma', false, dirname(plugin_basename(__FILE__))."/languages");
}
// Add actions
add_action('init', 'ap_action_init');
in my file where contact form is written i have this
_e('Prva','prijava_forma');
In my language folder i added .mo and .po files created with poedit.
Also i defined WPLANG in config.php, and change lang in admin section
But i get no translation. Where could be problem, i am new to this? | I´m using this code to get translated my themes: ` add_action('after_setup_theme', 'my_theme_setup'); function my_theme_setup(){ load_theme_textdomain('lc_realty', get_template_directory() . '/languages'); } ` the files are named **ru_RU.mo** and **ru_RU.po** I have no problems with this code on versions 3.3.1 to 3.8.3 I will upgrade to 4.0 soon son I hope this continue working well.
Also I have this code to translate the plugins in admin panel ` if ( is_admin() ) load_plugin_textdomain( 'myslider', false, 'myslider/languages' );
` this code goes inside the functions setup of the plugin | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
admin_head-post.php only works after publish / update
I have made a custom post type with some admin back-end. Currently I am calling scripts using the hook
admin_head-post.php
but this only seems to fire once a custom-post type has been created (on publish) or updated.
What is a better hook that runs on a specific admin page but when a new post is being initially created as well as updated / published etc? | There isn't a single hook for both, the new post page is `admin_head-post-new.php`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, admin menu"
} |
Multisite, can't see sub blogs
Based on advice I got from another question, I created a development copy of a multisite installation I've inherited inside of a Vagrant VM.
On a test site as described here...
!enter image description here
I get an error
!enter image description here
Could it be something in the .htaccess file?
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# uploaded files
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^[_0-9a-zA-Z-]+/(.*\.php)$ $1 [L]
RewriteRule . index.php [L] | The 404 is coming from your http server and not making it to WP. htaccess is not configured on your server. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, htaccess"
} |
Display all meta for a post?
I have a custom meta field for my posts and I'm able to display the value. But it only displays one row. Since I have more than one value I need to display all of them. I know I probably have to do some kind of for or while loop, but I don't know how to do it.
This is my current code:
$meta_value = get_post_meta( get_the_ID(), 'meta-text', true );
if( !empty( $meta_value ) ) :
echo $meta_value;
endif;
How do I change that snippet to display all rows? | To get all rows, don't specify the key. Try this:
$meta_values = get_post_meta( get_the_ID() );
var_dump( $meta_values ); // so you can see the structure | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "php, post meta"
} |
custom page or standalone page?
I'm new to WordPress. I have a requirement to implement a live calculator(results updated as you type) in a WordPress site. The site has a simple theme. What is the best way to implement this?
1. Adding the calculator using custom pages? or
2. Build a simple plugin for the calculator and use shortcode? or
3. Build a standalone single page and link to WordPress site?
Thanks in advance, | As Andrew stated, a custom page/template would be the most efficient way to display the calculator. You can leave this as a simple page, displaying just your calculator, or you can add in "the loop" below the calculator to display additional text which would be easily edited in Wordpress. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, shortcode, page template"
} |
wp_insert_post insert a post but return 0
I am trying to insert a page of a theme with after_switch_theme hook .Now when I set the page_template then it insert the post but return 0.
Is there a way to insert a page with specifying a template from the 'after_switch_theme' hook? | I found the answer. Actually I was passing the template in the `wp_insert_post`.
When I remove that parameter it returns the post ID. And with that post ID I used
`add_post_meta( $page_id, '_wp_page_template', 'tpl-favourites.php' );`
to set the template for that page. It is a common technique. I have just dig the code of a standard theme. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "wp insert post"
} |
Conditional Permalink based on category?
There have been unanswered questions about this here and in the WordPress support forum.
Is it possible to have a conditional Permalink structure for all posts in a category?
for example, `%year%/%category%/postname%` for a given category, but for the other permalinks have a different structure (without the year for example)?
I'm not very efficient with htaccess, I can use some help please.
Thanks! | **Answering My own question..**
That was easier than I though.. I used the `post_link` filter to modify the permalink in the following way..
function custom_permalink( $permalink, $post ) {
// Get the categories for the post
$post = get_post( $post_id );
$category = get_the_category( $post_id );
$post_year = mysql2date("Y", $post->post_date);
$target_cat = 6; // Category we'd like to change permalink for
if ( empty( $post_year ) ) return $permalink;
if ( $category[0]->cat_ID == $target_cat ) {
$permalink = trailingslashit( home_url( $category[0]->slug . '/' .$post_year .'/' . $post->post_name . '/' ) );
}
return $permalink;
}
add_filter( 'post_link', 'custom_permalink', 10, 2 );
And of course, flushing permalinks by visiting the settings > permalinks page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, htaccess"
} |
WordPress Woocommerce - Product Type
I have recently created a php script to import new products into Woocommerce. Please see how it was done here How to add product in woocommerce with php code.
The question I have is related to the **product type**. When you add a new product in the backend you can choose the product type: _simple, grouped, external/affiliate, and variable product_.
When I create new products with the script it uses the simple product type by default and I cannot find anywhere in the woocommerce database where I can change the product type to _external/affiliate_. **Does anyone know where that data is stored for each product?**
I check and double checked the posts and postmeta tables and cannot find anything related to the product type. I attempted a search in the options table but cannot find anything either unless it's encoded in there.
I appreciate any help :) | Products are Custom Post Types, so you can find it in wp_posts.post_type='product' || 'product_variation', etc.
!enter image description here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, woocommerce offtopic"
} |
Get custom category name from ID
I am having issues retrieving a custom category name. I already have its ID, which is coming to me from a custom field. I don't know if it makes any difference, but I'm using Woocommerce.
I'm trying to do this:
<?php get_term_by( 'id', $my_custom_cat_id, 'product-cat') ?>
But I get an empty value back, even though I know the category ID is correct (I am using it as query args already)
Many thanks | See the inline comments. Not tested. The following code will grab all the Custom Taxonomy Terms of Custom Taxonomy 'product-cat' and will show them one by one from the result array.
<?php
global $post;
$postID = $post->ID //get/put your post ID here
$getProductCat = get_the_terms( $postID, 'product-cat' ); //as it's returning an array
foreach ( $getProductCat as $productInfo ) {
echo $productInfo->name;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy"
} |
Using wp_add_inline_style without a stylesheet
I need to add custom inline styles to the header of a custom theme I'm creating. I've come across the `wp_add_inline_style()` function, which works but doesn't really suit me as it depends of a specific stylesheet. I'd need to add inline styles at the end of the head tag without a stylesheet dependency.
I've tried to set either the theme stylesheet or a non-existent one. In both cases, it works but it's a bit of a dirty hack IMO (either load the theme stylesheet twice or refer to a ghost file...). Is there a proper way to add inline styles in head without depending of a stylesheet?
Of course, I could add them directly in the header.php file but I'd like to avoid this. | You just need to add the styles directly to the page head. The best way to do this is to use the 'wp_head' action hook, assuming you are using a theme that has the hook. Like so:
add_action('wp_head', 'my_custom_styles', 100);
function my_custom_styles()
{
echo "<style>*{color: red}</style>";
}
Check out the WP codex to learn more about action hooks. | stackexchange-wordpress | {
"answer_score": 38,
"question_score": 31,
"tags": "theme development, wp enqueue style"
} |
Displaying user selected custom tags/taxonomies on the front-end
I would be grateful if anybody could point me in the right direction please.
I have a WordPress setup which utilises Theme My Login and < to allow users "tag" their user profiles from the front-end.
This works great but I am having difficulty displaying the user's selected tags when somebody is viewing their public/front-end profile.
I have the following code, which simply lists all the tags available - however I am unsure of how to alter this code so that it only lists the tags that the specific user has specified;
<?php
$args = array('taxonomy' => 'user_sector' );
$categories = get_categories($args);
foreach($categories as $category) {
echo '<div class="sector">'. $category->name.'</div>';
}
?> | If anybody needs to do this too - I was able to achieve this with the following code;
<?php
$terms = wp_get_object_terms( $userid, 'user_sector' );
foreach($terms as $term) {
echo '<div class="sector">'. $term->name.'</div>';
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, tags, profiles"
} |
Change theme's thumbnail to cropped WP featured image
The theme I'm using, when browsing a particular category, displays the full featured image (even if it's more than 1000px high), resized to `max-width:20%`. However, I'd like it to display just a cropped thumbnail that was autogenerated by Wordpress. Here's the relevant code:
while (have_posts()) : the_post();
$thumb = get_post_thumbnail_id();
$full_thumb = wp_get_attachment_image_src( get_post_thumbnail_id ( get_the_ID() ), 'original') ;
echo '<article class="search-entry clearfix">';
if ( $thumb ) {
$image = hb_resize( $thumb, '', 215, 140, true );
echo '<a href="'.get_permalink().'" title="'.get_the_title().'" class="search-portfolio-thumb"><img src="'.$image['url'].'" /></a>';
}
Is this possible? | Check out get_the_post_thumbnail()
$image_thumb = get_the_post_thumbnail( get_the_ID(), 'thumbnail');
Here's a more specific example:
while (have_posts()) : the_post();
echo '<article class="search-entry clearfix">';
$image_thumb = get_the_post_thumbnail( get_the_ID(), 'thumbnail');
echo ( $image_thumb ) ? sprintf('<a href="%s" title="%s" class="search-portfolio-thumb">%s</a>', get_permalink(), get_the_title(), $image_thumb) : ''; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, post thumbnails"
} |
current user can edit user?
I want to know if it is good practice to use:
if ( current_user_can( 'edit_user', $user_id ) ) {
// do something
}
because in Wordpress documentation a did not see this capability | Yes it can be good practice to check if a user is capable of doing something before doing something related in code.
For example, don't save a custom post type if the user doesn't have the capabilities needed to do it, or don't show certain things to users who don't have the `manage_options` capability ( super admins and admins normally ).
Bad practice in this case would be assuming the user has the necessary role to do these things and doing them anyway. This doesn't mean you should fill your code with checks for `current_user_can` everywhere though, in many places ( such as registering admin menus ), the check is performed by WP Core itself | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "users, capabilities"
} |
Minimize Performance Issues of MultiSite Large Number of Tables Created
I am deploying WordPress MultiSite and if I get a decent amount of users, I will have thousands of database tables to support all of these sites. I like the idea of consolidating all of these tables to a single set of tables to make multisite more manageable and also more optimized for SQL Server. Has anyone had experience with a large number of tables issue in multisite?
**Edit:** Basically I want to understand the performance impact of having thousands of tables added over time? | Well, WordPress.com it's the largest deployment of WordPress Multisite and they're basically using the same setup (multiple tables for each site), so you could say that it's a good strategy.
This kind of setup would let you to, for instance, keep your VIP users on a dedicated box, or add multiple DB servers as the network grows.
I've had experience with networks of about 500 sites and some basic tuning it's enough to keep the sites working.
Also, check the HyperDB plugin, which it's a replacement for WordPress' default DB class that "supports replication, failover, load balancing, and partitioning" | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, sql, performance"
} |
Why isn't the login page rate limited by default?
Brute force attacks seem to the be most common vulnerability on WP installs and rate limiting ought to be relatively easy to bake into WP itself as part of the official, default software (without the need to install a plugin). Why isn't this basic security feature included by default? | > Brute force attacks seem to the be most common vulnerability on WP installs
1. Brute force attacks are not WordPress vulnerability. They are password vulnerability, if bad passwords are used.
2. They are common, but if they are "the most common" in occurrences and, more importantly, breaches is questionable.
> rate limiting ought to be relatively easy to bake into WP itself
Had you _tried_ to bake this _easy_ thing? :)
I am yet to see login "security" plugin that didn't cause login issues long term, clashed with less than mainstream browsers, clashed with password manager applications, and so on. Ok, maybe there is one I can think of — for Google 2FA.
Anyone yet to demonstrate that _easy_ thing can be done reliably in plugin. Doing it at core scale? Ugh.
> Why isn't this basic security feature included by default?
So there you have it:
1. It's not basic.
2. It's not easy to implement.
3. It works just fine without it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "login, security"
} |
The problem with Wordpress Importer
I've tried many times to upload theme-unit-test-data.xml from < But when I'm trying to upload this file in WordPress Importer it gives me an error saying:
> Sorry, there has been an error. This does not appear to be a WXR file, missing/invalid WXR version number
I'm using the latest version (4.0) of the WordPress CMS.
**Edit:** I reinstalled the WordPress importer plugin and downloaded the Theme Unit test XML file multiple times with the same result. | It seems your XML file not valid. Try to import another xml and check. If another xml imports then its 100% issue with your XML in which you are getting error. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, posts, theme development, themes, xml"
} |
My homepage's width has reduced and I can´t fix it
I am creating a site for a friend of mine and I'm having trouble with the width of my homepage.
The homepage is set as a full width page but when you view it it only displays about 60% of the span. Before attempting to do this on my friend's server and domain, I used a domain of myown to show him a model and the model works just fine.
Here is the homepage Here is the model
I made another full widh page just to see if it wasn't the template, but that test page is OK (I wanted to show you the link but I'm not allowed)
I thought that maybe a plugin that I'm using (Widgetize pages Light) might be causing the problem, so I deactivated it for a while but the problem persists. Anyway, the same plugin is in use on the test site.
What coul be the problem? Please give me a hand.
Thank you in advance.
Pablo Alvestegui | The widths are the same the problem is that you have this in your `compressed.css` \- Line 55:
.column {
float: left;
margin: 0 10px;
padding: 0;
}
Whenever you float your column left you lose your max-width as it becomes inline. Fix that fix your website. The homepage content, or all the content is in that column class. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "templates, page template, homepage"
} |
WordPress sites got auto upgraded
With the release of WordPress 4.0.1 all my sites got auto upgraded even if none visited them and all those websites are behind browser authentication.
My sites are not broken but I am just curious to know how WordPress auto-upgrades the sites which are behind browser authentication. | In order for the update to occur, the site would have had to receive some form of traffic. Any traffic which loaded WordPress would do. Alternatively, anything which started the wp-cron.php process would trigger the update as well, like if you have it set to run that with a normal cron. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "automatic updates"
} |
WP + Google analytics = /search?
I finally found some time to tweak our business site. After digging some Google Analytic data I found out a portion of our users goes to "/search". Problem is: We don't offer a search function on our site as we aren't a webshop.
Does anyone know why or how Wordpress sends to /search? Is this when someone founds a 404 page or? | Search code comes with wordpress.If you remove search box it does not mean that search page is removed. If you want that google should not crawl your search page then you can specify in your robot.txt file like below :
Disallow: /search | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "search, google analytics"
} |
Delete tables from database when deleting plugin
I created a plugin and want to add a function to delete my tables from the database when a user deletes my plugin. I created a function that deletes tables from the DB when a user deactivates my plugin, but I don't want that. Here is the code:
// Delete table when deactivate
function my_plugin_remove_database() {
global $wpdb;
$table_name = "NestoNovo";
$sql = "DROP TABLE IF EXISTS $table_name;";
$wpdb->query($sql);
delete_option("my_plugin_db_version");
}
register_deactivation_hook( __FILE__, 'my_plugin_remove_database' );
As you can see, this function deletes tables when the plugin is deactivated, but I need to do that when the plugin is deleted. | You could do this using the WordPress uninstall.php support:
<?php
if( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) exit();
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS NestoNovo" );
delete_option("my_plugin_db_version");
?>
This uninstall.php file is called when your plugin is deleted. | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 16,
"tags": "plugins, database, customization, deactivated plugin"
} |
Get custom classes in Wordpress Navigation Menu
i'm a beginner to Wordpress. I have a question is how to get only classes we put in CSS classes box in Navigation Menu? Not all with the default Wordpress classes. The purpose of this is i want to make a FontAwesome icon before each list in Navigation Menu. | You can do this easy way or hard way. Hard way would be you creating custom functions to remove all menu classes and add `FontAwesome icons` accordingly.
And easy way would be this.
Go to Appearance > Menus
And add `FontAwesome icons` in menu items. Like this.
!menu
**Note:** You don't need to change page titles on each page. Just menu labels. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "menus, customization, icon"
} |
How can I remove the "Add New" button in my custom post type?
I have many custom post types that need the Add [custom post type] feature but I have a custom post type of "About" and I do not need to "Add New" about to the about custom post type. So I want to remove the button on top that says "Add About"
This is what I mean:
!enter image description here
Any idea how I can remove that? | Please refer below :
function disable_new_posts() {
// Hide sidebar link
global $submenu;
unset($submenu['edit.php?post_type=CUSTOM_POST_TYPE'][10]);
// Hide link on listing page
if (isset($_GET['post_type']) && $_GET['post_type'] == 'CUSTOM_POST_TYPE') {
echo '<style type="text/css">
#favorite-actions, .add-new-h2, .tablenav { display:none; }
</style>';
}
}
add_action('admin_menu', 'disable_new_posts'); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 12,
"tags": "custom post types, php, filters, wp admin"
} |
Making wordpress menu horizontal
Hey guys am new to wordpress development actually.I am trying to make my wordpress menu horizontal at the top below the title name.
My `header.php`
In my header file i have assigned the menus with a class like
<nav class="mythirdclass">
<?php wp_nav_menu(); ?>
</nav>
In my `style.css`
in the style.css file i have given like
.mythirdclass {
float: left;
width: 100%;
padding: 0;
margin: 0;
list-style-type: none;
display: inline;
}
But this code isnt working at all ..i want the menu to be appear in horizontal way.
Thanks for the help..:) | If I understood correctly you are trying to position output of `wp_nav_menu()` in horizontal line. Your should try styling `<li>` elements, instead of all `<div>`. Also `width: 100%;` should be removed.
Something like this seems to work:
.mythirdclass li {
float: left;
padding: 0;
margin: 1em;
list-style-type: none;
display: inline;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, themes"
} |
create a static folder independent with Wordpress
I have a website: www.a.com
I want to add a folder of code samples like this: www.a.com/code//index.html
So that at the end of each post I can refer the user to an example. How can I create a static folder independent with Wordpress that can be accessed from the outside? | Use the File Manager from cPanel or use a FTP account, and easily create your folder wherever you want and then direct the user with its real path something like:
It should work. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "htaccess, customization"
} |
Searching hook to set cookies before <head> and avoid "headers already sent"
I have written a plugin that sets cookies, and need to avoid the "Headers already sent" PHP error by placing the code at the very top before the head section. Themes usually place wp_head just before the close of the head section, so is there any efficient way to get a plugin to send this code without having to edit the theme itself? | For that I would suggest to use
'init'
hook.
According to codex
> This runs after WordPress has finished loading but before any headers are sent
For more details visit codex explantion and examples for this hook;
Codex link.
You can find answer to similar question over here;
How to set custom cookies before output | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "hooks, cookies, wp head"
} |
Override category permalink to match old non-WordPress links?
I am migrating a currently static website to WordPress.
The pages (I am using pages, not posts and categories) have the following structure:
Products (parent page)
- Product 1 (child-page)
- Product 2 (child-page)
- Product 3 (child-page)
Custom permalink is:
example.com/%category%/%postname%/
Generated links are:
example.com/products
example.com/products/product-1
example.com/products/product-2
example.com/products/product-3
Now for SEO reasons, the old link for Product 2 was
example.com/my-super-products/product-2
How can I override the category for this page without creating a new parent page with the desired name? | The Rewrite_API will let you modify the slug and URI at many levels. You might need to come up with a custom page template for Product 2 that assigns the '/my-super-products' slug, but this should work for you.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks"
} |
Adding text in more than one language (at the same time)
I am building a wordpress site. On the upper-right hand corner of every page on the site I am going to have two (or more) flags, and clicking on any given flag should cause the site to display the text in the language corresponding to the given flag. In order to do this, I should be able to enter the text for WordPress pages, posts, blogrolls, etc... in all supported languages at once.
How does WordPress achieve this? (I also want to make one language the default so that if one text is missing in one language then it is displayed in the default language, but I would like the admin interface to be flexible enough so that any given text must be entered in both (or all supported) languages at once, with a single submit.
Do I need a plugin to achieve this behavior? How can I achieve such a setup?
Thanks. | WordPress doesn't have built-in features for a site that is served in multiple languages. Yes WordPress has features for translating the UI labels into different languages, but not for the actual content. You are going to need to use a plugin that basically keeps multiple versions of each Post for each language and has means for the user to select the language. The WordPress Codex has an article that overviews the different ways to achieve a multilingual setups.
**Articles to help you pick a plugin**
* The Complete Guide To A Multilingual WordPress Site
* How to Create a Multilingual WordPress Site
* Top 6 Translation Plugins for Your WordPress Site | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "admin, wp admin, multi language, language"
} |
Does anyone know all parameters of get_comments()
Here is the link. There is a lot of parameters that didn't explain yet, and I want to know all about it. Thought, I have try to read the code, but can not understand it at all. The more I try to read code, the more queries I have.
Does anyone know about those parameters? Especially 'parent', 'post_parent', 'fields', 'include_unapproved', 'comment__in', 'post__in'.
Plz help me, and I really appreciated. Thank you for reading my question. | * parent : Comments can be replies to other comments. Every comment has an ID number. When the comment is a reply, then it will have a "parent" which is the ID of the comment it is replying to. Putting a comment ID in here will get all the replies to that comment.
* post_parent : Posts can be children of other posts as well. This is how things like hierarchical pages work. Putting an ID in here will get all the comments that are made to all the child posts of that ID.
* fields : Determines what comment fields you want to get back. If you only want the Comment IDs, for example, you would put "ids" here.
* include_unapproved : Whether to include unapproved comments or not. True/false.
* comment__in : An array of comment IDs that you want to get.
* post__in : An array of post IDs that you want to get the comments of. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, comments, comment form, parameter"
} |
Check if is on child-page of a particular page
I am trying to output a logo depending on which page is being viewed.
<?php if ( is_page('home') || is_page('services') ) { ?>
<div class="col-md-2 col-sm-4">
<?php ci_e_logo('<h1 class="logo ' . get_logo_class() . '">', '</h1>'); ?>
</div>
<?php }
else { ?>
<div class="col-md-2 col-sm-4">
<h1 class="logo imglogo">
<a href="
<img src="<?php echo get_bloginfo('template_directory');?>/images/picturehere.png" alt="title here"></a>
</h1>
</div>
<?php } ?>
The code above works fine, but how do apply the logo image swap on the sub-pages of the 'services'? | <?php
global $post;
if ( is_page('home') || is_page('services') ) { ?>
<div class="col-md-2 col-sm-4">
<?php ci_e_logo('<h1 class="logo ' . get_logo_class() . '">', '</h1>'); ?>
</div>
<?php }
elseif ( preg_match( '#^service(/.+)?$#', $wp->request ) ) { ?>
<div class="col-md-2 col-sm-4">
<?php ci_e_logo('<h1 class="logo ' . get_logo_class() . '">', '</h1>'); ?>
</div>
<?php
}
else { ?>
<div class="col-md-2 col-sm-4">
<h1 class="logo imglogo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<img src="<?php echo get_bloginfo('template_directory');?>/images/picturehere.png" alt=""></a>
</h1>
</div>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 14,
"tags": "pages, child pages"
} |
Restrict access to admin
Iuse this code for restrict access to wordpress admin. But now i must allow access to author too. Only for this roles. Is possible with this code? Really thanks
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
if ( is_admin() && !current_user_can( 'author' ) && !( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
wp_redirect( home_url() );exit;
}
} | Following plugin can help you better and quick :
| stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin"
} |
How to set parameters for search loop?
This is the loop from search.php file:
if (have_posts()) {
while (have_posts()) {
the_post();
I tried to set parameters like this:
$wp_query->set('post_status', 'publish');
but it doesn't work. | You can modify search query and set your parameters with the help of `pre_get_posts`. Like this.
function wpse_custom_get_posts( $query ) {
if ( is_admin() || ! $query->is_main_query() )
return;
if ( $query->is_search() ) {
$query->set( 'post_status', 'publish' );
}
}
add_action( 'pre_get_posts', 'wpse_custom_get_posts', 1 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
How do I sort a WP_USER_QUERY by multiple meta fields?
I've got the following WP_USER_QUERY in WordPress:
$args = array(
'orderby'=>'meta_value',
'meta_query' => array (
0 => array(
'key' => 'last_name',
'value' => 'smith'
),
1 => array(
'key' => 'first_name'
)
),
);
$user_query = new WP_User_Query($args);
It's working in as much as it's returning the records I'm expecting it to, but the `orderby` is off - it's only sorting by their last name, and ignoring the first. How do I search by multiple custom user meta fields in this sort of query? | Short answer: you can't. I had to write a custom query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user meta, wp user query"
} |
Should I sanitize an email address before passing it to the is_email() function?
I'm using `is_email()` to check if a user-provided email address is valid. For example:
$email = $_POST['email'];
if ( is_email( $email ) )
// Do something.
To the best of my knowledge, nothing in this function writes info to the database. Should I be sanitizing `$email` before I pass it to the function? | Looking at the `is_email()` functionality on trac, it looks like you don't need to sanatizie as it's just string testing. I would even go so far as to say that if this function returns true, you wouldn't need to sanitize it before sending it into the database. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 13,
"tags": "sanitization"
} |
How do I properly update the WordPress database password?
A site that I manage was recently compromised, and I am going through the steps to harden and re-secure the site. I would like to change the MySQL database password and want to make sure I do not take the site down (for more than a minute).
I am also concerned that if I manually change the database password directly in the **wp-config.php** file that it will be visible and un-encrypted. For example, if my initial password at install was " _please_ " it would display in the **wp-config.php** file as " _aDQps4txy_ ".
So what is the best way to go about updating the database password? | This is technically challenging. WordPress _must_ have access to your DB password in plain text. Having access to the `wp-config.php` contents is already a breach of security in progress.
There are alternate approaches to configuration, such as loading credentials via environment variables, but in practice they are used exceedingly rarely because PHP's configuration file is a reasonable solution already.
It's not clear why you assume someone will get access to the configuration file. As a low-hanging fruit, you can place it outside of the web accessible directory. WordPress will scan for the configuration file up one directory level above itself. For subdirectory installs, you could use `require` to load configuration content from elsewhere, but even that is rarely done. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database, mysql, security, password"
} |
If is custom post type archive page
If I need to check custom post post type is movie, I can use following code.
if ( 'movie' == get_post_type() )
I need to check, if it is **custom post post type Archives Page**? ( www.domain.com/movie) | Check out is_post_type_archive() in the codex
if( is_post_type_archive('movie') )
{
//do my thing
} | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 7,
"tags": "custom post types"
} |
Remove images from the_content
I'm trying to show only content with all paragraphs (possibly divs,...) but with no attached images.
I had some success with:
echo preg_replace('/<img[^>]+\>/i', '',get_the_content());
But it removes paragraphs not just images.. Any idea why? | Your function is not removing the p tags: they have not yet been added as `get_the_content` returns the unfiltered content. You can manually add the p tags using wpautop.
$unfiltered = preg_replace('/<img[^>]+\>/i', '',get_the_content());
$filtered = wpautop($unfiltered);
echo $filtered; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "the content"
} |
Execute upgrade-theme with coding
I'm executing some functions remotely from xmlprc with wordpress.
I would like to run upgrade-theme remotely for theme that I develop.
Assume that wp knows there is new version of theme. pre_set_site_transient_update_themes
What is the true function to call. And how to call it? | To whom it may need.
Here is the codes.
I hope it helps someone.
function force_theme_update($update){
$update->response['active3'] = array(
'theme' => 'active3',
'new_version' => date('Ymd'),
'url' => '
'package' => '
);
return $update;
}
if(current_user_can('manage_options')){ add_filter('site_transient_update_themes', 'force_theme_update'); } | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, updates, upgrade, xml rpc"
} |
How to set 301 redirection after moving WordPress blog?
I have moved my wordpress blog to new domain.
Old Address : **domainname.com/blog** | New Address : **newdomainname.com**
Please pay attention about **old address and new address**.
Now I want to redirect all old pages to new blog ( should be 30 redirection).
I could not find way to do it properly because I moved my blog to new domain from old domain directory.
Thanks | ### WAY #1 - cPanel
I assume your host is using cPanel managing your Server.
Browse `domainname.com/cpanel`, login their with cPanel credential:
!enter image description here
Change the values according the following image:
!enter image description here
Don't forget to check the "Wildcard Redirect" to redirect all the subfolder/subpages also ( _Thanks to @RobertHue_ ). _Add_ the redirection and you are done.
### WAY #2 - `.htaccess`
Open up your `.htaccess` of `domainname.com/blog/` in edit mode. Put the following code there (I made it using WebConfs.com Redirect Generator):
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) [R=301,L]
Save it. And _yala_!
## EDIT
That's well said by @RobertHue. I did not mention the subfolder or subpages redirection. So I edited my answer, changed the attached images and posted new code. Thanks a lot @RobertHue for pointing the important things. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "redirect, htaccess, seo, wp redirect"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.