INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Menu administration, how to allow special charachters
I'm new to wordpress, i have created a website, for multilanguage solution i use qTranslation, my menus has also description and this is a problem, how can i allow special charcters here:
Here is link for image of my problem: <
my code look so, but after saving are this charachters missing and a see content from both languages:
<!--:fr-->french content<!--:--><!--:it-->italian content<!--:--> | What kind of special characters do you need to put?
I never used this field in Wordpress, so I'm not sure of what I am saying, but maybe it works like in HTML, which needs you to use entity codes for letters like à, é, è, etc.
Here's a link to a list of entity code : <
Hope it helps...! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
WordPress display name string manipulation
I have set the display name to show both first name and last name using the function below. How do I manipulate the LAST NAME to only pull the first letter of that string? Example, if you sign up as John Doe (First name= John, Last name= Doe), I want your display name to be John D.
Thanks
function force_pretty_displaynames($user_login, $user) {
$outcome = trim(get_user_meta($user->ID, 'first_name', true) . " " . get_user_meta($user->ID, 'last_name', true));
if (!empty($outcome) && ($user->data->display_name!=$outcome)) {
wp_update_user( array ('ID' => $user->ID, 'display_name' => $outcome));
}
}
add_action('wp_login','force_pretty_displaynames',10,2); | Use PHP's `substr()` function:
$outcome = trim(
get_user_meta( $user->ID, 'first_name', true )
. ' '
. substr( get_user_meta( $user->ID, 'last_name', true ), 0, 1 )
. '.'
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, profiles"
} |
Change Width of Featured Image Thumbnail on Add/Edit Post Page
Does anyone know of a way to change the width of the featured image on the edit post/add post page? I want to make it 50px wide. I'm not talking about the front page of the website, but the back end where you've selected the feature image and it sits next to your post as you're typing. Thank you! :) | Okey i think i understand what you want to do.
Here is a function that changes the html-output of the feature image in admin. It will look for the attached feature image ID and output it by using wp_get_attachemt_link() so you can change the size by the parameter $size. Here is a function that should work:
function wpse_111428_change_feature_image_admin( $content )
{
global $post;
$size = 100;
$id = get_post_meta( $post->ID, '_thumbnail_id', true );
if( $id )
{
return wp_get_attachment_link( $id, array( $size, $size ) );
}
}
add_filter( 'admin_post_thumbnail_html', 'wpse_111428_change_feature_image_admin' );
I found the original code in `\wp-admin\includes\post.php` that WordPress uses to output the feature image. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, images"
} |
WPMU - new users are automatically subscribed to the main blog - how to prevent that?
New users added via `wpmu_signup_blog($domain, $path, $title, $user_name, $user_email);` are automatically subscribed to the main blog. Can this be prevented? I only want them to be administrators of their newly created blog.
I have no idea where to start looking for that as it seems to be some internal WordPress's mechanism that handles that.
< | This is a known bug.
A fix will be available in 3.6.1, see: <
For now, either bulk remove the users in WP Admin or do something (ugly and temporary, remove when 3.6.1 is available) like:
add_action( 'wpmu_new_user', function ( $user_id ) {
global $current_site;
remove_user_from_blog( $user_id, $current_site->blog_id ); // remove user from main blog.
} ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "multisite, users, user roles, user registration"
} |
How to customize categories panel?
!enter image description here
how to customize this screen ? example : add new area or remove description section | First you have to find the right action to hook into. I find it by look into `class-wp-posts-list-table.php` the columns is in an array so you just have to find the right key and unset it by php-function `unset`.
Here is a example that removes all of the columns:
function wpse_111473_remove_category_columns( $defaults )
{
unset( $defaults['description'] ); // Description
unset( $defaults['slug'] ); // Permalink
unset( $defaults['posts'] ); // Posts count
return $defaults;
}
add_filter( 'manage_edit-category_columns', 'wpse_111473_remove_category_columns' );
!enter image description here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "categories, columns"
} |
How to get Menu Navigation Labels to output HTML
I'm trying to follow Jason Bradley's advice on how to style my Wordpress menus.
Specifically, I want to insert an icon before my navigation items using Font-Awesome.
I tried putting this code in the Navigation Label field for my "Home" link:
<i class="icon-fixed-width icon-home"></i> Home
However, when I view the page in my browser, it displays the HTML verbatim, it doesn't interpret the tag, or any other HTML I throw at it, for that matter.
Did Wordpress Menus change in 3.6? Am I missing something obvious?
I know that my font-awesome installation works because I am using their icons all over my site. Thanks. | The "Navigation" field is _not_ where you want to place your CSS class. The navigation is what the user will see in the menu, so don't put any code there.
To enter a custom CSS class to your item, you need to do the following:
* Click the "Screen Options" tab in the top right corner of the page.
* Under "Show advanced menu properties", tick the "CSS Classes" checkbox.
* Now for every menu item, you have a field labelled "CSS Classes (optional)" where you can enter "icon-fixed-width icon-home".
Job done! :) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "menus, navigation, icon"
} |
Share WordPress Database
Does the WordPress installation has to use an exclusive database? I'm building a website with custom pages, that access a MySQL database. But the site will also have a WordPress installation. Can I use the same database unique for WordPress and the custom pages? | > Does the WordPress installation has to use an exclusive database?
If there are no table name conflicts, WordPress can share a database. Preventing conflicts is just a matter of setting a database prefix on install. By default, that prefix is `wp_` but you can change it to anything you want within reasonable character limits. It should be no problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, customization"
} |
How do I apply my CSS to a theme page?
I installed the Mog theme for WordPress and I would like to position some of my pictures on a page using HTML divs and CSS. My question is, do I have to create a child theme of the Mog theme in order to do this? Or can I just add my own css to the particular page? If so, how do I incorporate my own css for this particular page? If the Mog theme is updated, how will this update affect my page contents? | If you want to keep your changes while allowing Mog theme to keep updated you will need to create a child theme. This will ensure your changes are kept. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "themes, css, html"
} |
Pods custom type integration with navigation menu and current_menu_parent
I have a Pods type called `project`, and a Pods pages url as `project/*` (which links to a template to show the project).
I also have a normal Page which lists the projects (via a custom shortcode that loops through all the pods) and outputs on the page.
My navigation menu is simple: Home, About Us, Method, Our Work, Contact Us.
I need further guidance please on how to link up the Pods `project/*` page so that when a specific project is being displayed, the top level Projects link is highlighted with the correct wordPress class `current_menu_parent`.
Also where should the Pods page be listed in the Wordpress Appearance -> Menu, as I see no link there for the Pods type.
How can I do this please?
!unable to link pods custom type to nav menu | Advanced Content Types and Pod Pages are separate from WordPress post types. They do not currently show up in the navigation menu management area. This is a feature we are working on including in the future.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pods framework"
} |
Spams, Scams on WordPress site - what to do?
Suddenly our hosting company complaint our boss with a google mail that saying something like:
> **Your site is full of spam/scam. Please remove such malicious thing or we will unlist your site.**
That made us crazy. We found some links in our WordPress site is taking us to a page, that is obviously NOT our site-page. But with the same URL of our page (domain/my-page) it's showing someone other's contents - that's disturbing too.
We tried the cPanel's "Virus Scanner" to find any trace of virus attack to the site, but found nothing.
Then, one of our developer found a way to generate a new page for the content of that page with a slightly different slug, and that worked. But after days it's worthless.
How can we get rid of such spam/scam? | One of our developer Mr. Ahsan Ullah found a very normal solution to that: He simply **Refreshed the Permalink settings** and it's all set.
From `/wp-admin`, going `Settings` » `Permalinks`, he clicked the `**Save Changes**` button. The permalink structure of the whole site was refreshed and the unwanted links were vanished from the site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "spam"
} |
How to display Yoast SEO meta description in archive template for each post instead of the_excerpt()?
I read this question but it wasn't what I was looking for exactly. I'm new to Wordpress and a little confuse with the functions and everything.
How can I get the metadescription in the loop for each post?
Thanks ! | Add the following code in the archive template loop to display Yoast SEO meta description for each post.
echo get_post_meta(get_the_ID(), '_yoast_wpseo_metadesc', true); | stackexchange-wordpress | {
"answer_score": 46,
"question_score": 31,
"tags": "loop, post meta, plugin wp seo yoast"
} |
Problem code and show comments
**I use this code in shortcode for show posts :**
<?php
while ($wp_query->have_posts()) : $wp_query->the_post();
$imagen = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), "medium");
$ruta_imagen = $imagen[0];
if ($ruta_imagen!="")
{
$ruta_img="<a href='".get_permalink($post->ID)."'><img src='".$ruta_imagen."' width='".$img_width."' height='".$img_height."' class='image_car'></a>";
}
echo $ruta_img;
endwhile;
?>
This code works perfect inside the code for create the shortcode , but the problem it´s if i use the shortcode and put active the comments for ones post or page , the form and comments no show
I don´t understand what have bada this code for no let show the comments , if i don´t use this shortcode the comments show other time and the form
Please if you can tell me which it´s the problem perfect for me
Thank´s , regards ! | This question is very hard to understand but I think that you might need to put `wp_reset_query()` or `wp_reset_postdata()` after your Loop (after `endwhile;`) to to reset the loop and/or the `$post` variable. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, shortcode"
} |
spacing disappears on posts when importing
This is a random question, so I'll be lucky if there's an answer out there.
I imported this wp site from another location, and for some reason, none of the posts show spacing between paragraphs anymore. If you look at any post, you'll see there is no space between each paragraph. In the actual post, on the backend, the spaces are all there. Each paragraph has a nice space between it. On the actual site, the spacing disappears. What gives?
This is the case with all of her posts, so I'd be just delighted if there is some solution to the issue.
it's at: www.travelwithcastle.com and it's a twentytwelve child theme
Kelly | As Sven noted in the comment, your theme doesn't have any spacing after paragraphs. It's actually set to no space between paragraphs on line 797 of your style.css. If you were to change that line and the one above it so the last numbers in each line were 10px and 1rem, you'd have fairly default spacing back.
The spacing in the admin is controlled by a different stylesheet, likely the default one in your case. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
two sites, same code, different presentation
I have created two web sites. One is "production" and the other "dev". Each is a virtual host and both are on a single server running apache. Both sites are loaded with the same code base: WP 3.5.1, a base theme and a child theme. This is not a multi-site setup; just two sites loaded in different directories.
The page in question uses a page template. In the page template there is some switching in PHP code to choose what to display. The switching is based on the $current_user->ID. If ID is null or zero display a logon block otherwise look up some data to present.
This works fine on the dev site. It does not work on the production site. Something is different. I checked .htaccess, the virtual host declaration in apache, and the settings for WP and the theme. They all appear to be the same. I have run delta checks on the code and the two sets of files are identical.
What other config settings might be in play here? | After walking through the code and examining everything else, I (finally) revisited the page definition in the Dashboard. There I noticed that the page was not associated with the page template I was working with. I assume that during the migration from the development web site to the production web site, the association went missing.
FTR, "PBKAC" stands for **p** roblem **b** etween **k** eyboard **a** nd **c** hair. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, virtual hosts"
} |
How do I make a copy of WordPress to other folder
Currently I have my WordPress up and running fine on the root folder of my production server. Now I would like to copy almost everything (except database and url) into other folder for testing purpose, lets say `/newsite`.
1. What's the most convenient way to do this ?
2. Do I have to play with the `.htaccess` file ? At this moment I don't even use this file on the production server, Is this bad ?
3. Will Wordpress multisite be able to separate production and development site ? How about the database separation ?
Basically in the end I would want to have
* www.mydomain.com as the main site
* www.mydomain.com/newsite as the testing site
I have full access with FTP. Any help is greatly appreciated. | If you want to move wordpress you should this: <
I guess you want to create a development environment, and because you never edit core files of Wordpress you don't have to copy Wordpress itself because the only thing you are changing is the theme folder. And you don't want to install Wordpress a second time in a sub-directory so maybe you should try **creating a sub-domain** : < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, migration, directory"
} |
Displaying products from categories in woocommerce
I want to display thumbnails of multiple categories on a page, i am having hard time accessing the categories as it shows empty. is something wrong with my code?
$args = array(
'per_page' => '12',
'category_name' => 'travel',
'orderby' => 'title',
);
print_r($args); //nothing gets output, like categories
$query = new WP_Query( $args );
if( $query->have_posts()) : while( $query->have_posts() ) : $query->the_post();
print_r($args); //nothing gets output, like categ
//want to display the thumbnail
endwhile;;
endif; | You're passing bad array keys to `$args`. Do something like this:
$args = array(
'posts_per_page' => '12',
'product_cat' => 'lead-generation',
'post_type' => 'product',
'orderby' => 'title',
);
$query = new WP_Query( $args );
if( $query->have_posts()) : while( $query->have_posts() ) : $query->the_post();
the_post_thumbnail('full');
//want to display the thumbnail
endwhile;
endif;
There is no `per_page` key, use `posts_per_page` instead.
Woocommerce category taxonomy slug is 'product_cat'. The 'category_name' is for normals posts. You must target the post type of woocommerce, here it is `product`. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "plugins"
} |
how to change user roles for users who doesn't have any. (about 8000 users)
We have about 8000 users who doesn't have any roles. we need to change them to "contributor". How can I change them to "contributor"? Should I do on database? if so, which fields I need to update?
Thanks, | You can do it by executing simple SQL query:
UPDATE wp_usermeta
SET meta_value = 'a:1:{s:11:"contributor";b:1;}'
WHERE meta_key = 'wp_capabilities'
AND meta_value = 'a:1:{s:10:"subscriber";b:1;}'
This query will updated all subscribers to be contributors. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "user roles"
} |
items_wrap not working
I registered a wordpress menu this way:
function nothing_register_menus() {
register_nav_menu('header-menu',__( 'Header Menu' ));
}
add_action( 'init', 'nothing_register_menus' );
I am calling wp_nav_menu that way:
wp_nav_menu( array(
'theme_location' => 'header-menu',
'container' => false,
'echo' => false,
'menu_class' => 'nav-menu horiz-menu container',
'items_wrap' => '<ul class="sixteen columns">%3$s</ul>'
) )
But the output always looks the same. The menu class is correct, but the wrapping ul never has a class. | your problem is in your use `'menu_class'` and `'items_wrap'` not synchronized.
You can edit :
wp_nav_menu( array(
'theme_location' => 'header-menu',
'container' => '',
'echo' => '0',
'menu_class' => 'nav-menu horiz-menu container sixteen columns',
'items_wrap' => '<ul class="%2$s">%3$s</ul>'
) )
or:
wp_nav_menu( array(
'theme_location' => 'header-menu',
'container' => '',
'echo' => '0',
'items_wrap' => '<ul class="nav-menu horiz-menu container sixteen columns">%3$s</ul>'
) )
Apologize for my English is bad ! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, menus, navigation, user registration"
} |
How to make permalinks update from code?
I have made made a theme that has some 'virtual' pages made with url_rewrite. Is there any way of updating the permalink options at theme install so the pages are availble from start, with out requiring the user to update them from Dashboard? | This question is difficult to understand but I think what you want is to run `flush_rewrite_rules()` on theme activation. I don't believe there is a specialized hook for this but both @Rarst and @toscho have posted good methods in another answer. You should be able to easily adapt that code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, permalinks"
} |
Is wp_is_mobile() effective?
I'm going to test the user agent to load a mobile template instead of the desktop theme.
There are many mobile detection scripts out there.
* Does `wp_is_mobile()` function work well?
* What is your experience in comparison with other classes like e.g. `mobiledetect.net`? | Yes it works well. It's a very simple function but never found a mobile device not recognized by it. It recognize the 90%+ of mobile devices. Main difference from mobiledetect.net is that doesn't differe from phone and tablets.
See the code | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 17,
"tags": "theme development, mobile"
} |
Bold letters inside excerpt
I'm currently trying to get some of the words that are inside an excerpt to be bold with "h1" tag but it does not seem to be working. When I checked online, all that I come ac cross was the suggestion to use a plug in. Is there a way to achieve this without a plugin. My CSS looks as shown below.
.side-bar h1 {
font-weight: bold!important;
} | 1. You may already know this, but the `<b>` or `<strong>` tags are better choices if all you want to achieve is bold text. `<h1>` should be reserved for the most important header(s) on your page.
2. By default, WordPress strips out a lot of what's in excerpts, including images and HTML tags. To undo this, you'll need to create or edit your theme's `functions.php` file. Either of these links will give you a description of how to write/edit `functions.php` to achieve this and other changes to the excerpt:
* <
* < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, excerpt"
} |
Displaying just one post from each category on archive page
My categories look like this. Each has one or more posts
-Main Category
--Main Category Sub-category 1
--- 1 post here
--- 1 post here
--Main Category Sub-category 2
--- 1 post here
--- 1 post here
--- 1 post here
--Main Category Sub-category 3
--- 1 post here
When viewing Main Category archive page I only want the first post from each of the subcategories. So in my case I would only have 3 posts. Using twentythirteen theme. Don't want to change too much. I hope it can be done with query_posts.
<?php /* The loop */ ?>
<?php query_posts($query_string . '&??????'); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content-category', get_post_format() ); ?>
<?php endwhile; ?> | Don't use `query_posts()` use the `WP_Query` class instead... the link to the Codex will also reference all the appropriate query parameters.
The following would query the most recent post in a particular category, you will need to define the `$category_id`
// The Query
$query = new WP_Query( 'cat' => $category_id, 'posts_per_page' => 1 );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
get_template_part( 'content-category', get_post_format() );
}
}
/* Restore original Post Data */
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
Buddypress registration page hangs
Installed fresh set of wordpress and buddypress. Enabled user registration.
Trying to register user. But the page hangs and if seen in Network tab of chrome, the status shown is pending waiting for the response from the server.
But in wp_users, this user record is created successfully. The only issue is, the page hangs and takes the user to no where.
Is this supposed to be an issue with buddypress / some settings that I am missing? This is the issue in IE, Firefox & chrome (that I tried)
Below are the environment details
Wordpress version 3.6
Buddypress version 1.8.1
Wamp server
Any kind of help / suggestion is appreciated. | I re-installed the wamp server with the latest one. This fixed the issue. Looks like this was the issue with Apache. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "buddypress, user registration"
} |
Disable all https in WordPress
Recently I moved my WordPress to another server (MediaTemple), but now my admin is redirecting for HTTPS all the time, but I don't have SSL enabled on my domain, so it just keep warning that is not the same server and bla bla bla... Well, I want to disable all those https request on WordPress. How can I do that? | I don't believe WordPress sends `HTTPS` requests unless it has been told to do so. It sounds like you need to undo some previous configuration -- most likely change/remove the `FORCE_SSL_LOGIN` constant.
You may have plugins participating as well though. Make sure to check that.
# Reference:
< | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "admin, ssl, https"
} |
Given a page ID, how to display entire page (header/content/footer/sidebars) from a plugin hook
Given a page ID it it possible to display the page content from within a plugin hook.
I would like to know if it is possible to display the **_entire_** page given a page ID (Header/Footer/Sidebar/Content/etc..)
For example, if the Page ID "123" is the "Home" page then the output from `render_entire_wordpress_page(123);` would be identical to visiting the normal "Home" page. If the Page ID "321" is the "Blog" page then the output from `render_entire_wordpress_page(321)` would be identical to visiting the normal "Blog" page.
Is this possible?
I can somewhat achieve this by filtering `rewrite_rules_array` and then flushing, however I'm trying to output this content after all rewrite rules have finished processing. | > I would like to know if it is possible to display the entire page given a page ID
Yes, ` or ` Request that address via AJAX or the HTTP API.
WordPress pages render on page load. There is nothing that I know of that "pre-renders" a page that would let you grab the whole generated source without a request to the server for it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "templates, hooks"
} |
How do I determine if the user who registered is not spam?
I've recently set up a forum on my site with the bbpress-plugin. Now a user has registered on the site but the email-adress looks suspicious to me. How can I determine if the user is real? Is there a security risk if it is spam and I do not remove the user? Thanks | * Require that emails be verified before registration is completed.
* Captcha
* Use Honeypot Project
* Install Akismet
* Require Facebook, Twitter, or another service for registration.
You won't be able to stop all spam but you can fight the majority of them. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, security, bbpress"
} |
Wordpress and WebRTC?
I'm pretty new to WordPress and I was wondering about WebRTC integration : user permissions, page integration... I'm especially interested in chat communications (writing and audio, video is not my first concern). At the moment the only available plugins are about video communications and use an external solution (service).
Does someone have already addressed this topic and would share some hint? | After some researches I came across two plugins using WebRTC :
* Collaboration, which is a simple integration of TogetherJS
* wpRTC which is not enough mature yet but look promising ! | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 2,
"tags": "plugins, audio, customization"
} |
How to know if it's a child taxonomy?
I'm in need to know if the current taxonomy is child or parent. How can i achieve this?
I need it for the condition in if statement. I need to know
if(this is child taxonomy){
}
Anybody knows how? | You may be using this piece of code, found in the WordPress support articles and which you can see here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "categories, custom taxonomy"
} |
add_user_meta() vs update_user_meta()
I'm looking at the docs for `add_user_meta()` vs `update_user_meta()`.
If the current meta_key does not exist for a user, will `update_user_meta()` automatically add the meta_key for that user or do you have to define the meta_key with `add_user_meta()` first? | You have already found out that using `update_user_meta()` if the meta field for the user does not exist, it will be added. ie `update_user_meta()` can do the task of `add_user_meta()`
However, the difference between them is the `return values`
## update_user_meta()
returns **False** if no change was made (if the new value was the same as previous value) or if the update failed, umeta_id if the value was different and the update a success.
**NOTE: as of v3.4.2 it returns the umeta_id on success (instead of true) and false on** failure
## add_user_meta()
return **Primary key id for success**. No value (blank) for failure. Primary key id for success. | stackexchange-wordpress | {
"answer_score": 21,
"question_score": 12,
"tags": "user meta"
} |
loss of theme options while site deployment in production
i have moved both wordpress folder and the development database on a distant server. Why all my theme options are lost ? where are these options stored if not in wp_options table nor wp_files ? | this has something to do with data serialization and the fact that i have search and replace on my entire database to change the URLs,
see the "When Your Domain Name or URLs Change" section of
| stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, options, deployment"
} |
What does short_ping do?
Since WP 3.6, you can do `short_ping` on comments as you can see <
I want to use it for my new website ZorgWijzer.nl, but I am not really sure if this is good or bad for SEO. Can someone tell me where I can find more information? | If the comment is a pingback or a trackback and short_ping is `true` then the comment is processed by the `ping` method which formats the comment differently than either the `html5_comment` method or the `comment` method both of which create a much longer more complicated format than does the very minimal `ping` method.
You can kind-of guess what it does by the name of the variable, really, but when in doubt there is no better source of information than the source code itself. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "seo"
} |
Set template based on query in URL
I want to be able to force WordPress to load an page/post based on a query in the URL.
`www.mywordpresssite.com/posts/myarticle?template=custom`
This URL should load the _myarticle_ post using template `custom.php`
I don't even know where to start with this one. Is there a hook I can use to change the template in my theme before it loads?
Any help is appreciated. | There are a number of template filters available to override template selection. For a single post you can use the `single_template` filter:
function wpa_single_template( $template ) {
if( isset( $_GET['template'] ) ) {
$template = locate_template( $_GET['template'] . '.php', false );
}
return $template;
}
add_filter( 'single_template', 'wpa_single_template' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "templates, hooks, urls"
} |
How to get custom metabox image field?
i have custom metabox with the image field, i can upload image from wp-admin to this metabox, metabox code
array(
'name' => 'Burst Image',
'desc' => 'Crop your image to exact dimension before upload!',
'id' => 'burst_img',
'type' => 'image'
)
i have code like `$burst_img= get_post_meta( $post->ID, 'burst_img', true );` to get the metabox , but it doesn't work, how can i get the metabox image ? | Normally, the WordPress function for displaying the image of your custom meta box is this `<?php wp_get_attachment_image_src( $attachment_id, $size, $icon ); ?>` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "custom post types, custom field, metabox"
} |
get the_title_attribute by id
I'm creating a list with a few permalinks which I call to with `<a href="<?php echo get_permalink($id); ?>" title="...`. And for the title I want to call `the_title_attribute()`. But it seems it can only be called within a loop, and not by id. How do I correctly get a title attribute?
_Note: The reason I want to use`the_title_attributes();` is because I use html tags within some of my titles._ | hey just look in code and it also support fourth parameter `post`
global $post;
the_title_attribute(array('post'=>$post));//post object
or
global $post;
the_title_attribute(array('post'=>$post->ID));//post id
so you can use it like
<a href="<?php echo get_permalink($id); ?>" title="<?php the_title_attribute(array('post'=>$id)); ?>"> //where $id is post id
**Important Link**
the_title_attribute | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "permalinks, id, get the title"
} |
Custom single page based on which custom page template is selected
I have two custom page templates ("template-blog-left.php" with the sidebar of the left side, and "template-blog-right.php" with the sidebar on the right side.) but I don't know if there's any way of creating a custom single post template for each of them, so that If I select the "template-blog-left.php" for my "Blog" page, then the single page should have the sidebar on the left.
So, in other words, is it possible to have a custom single page being selected automatically every time I make a post, based on the custom page template that is selected for the "Blog" page. | Yes it is possible using `get_template_part();`
Assuming that you use a standard single.php:
<?php
/*
* Template name: template-blog-left
*
*/
get_header(); ?>
<div id="left-sidebar">
<!-- Here your left sidebar -->
</div>
<div id="content">
<?php
//This function will look for single.php file in your theme folder
get_template_part( 'single' );
?>
</div>
<?php get_footer(); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, pages, templates, single"
} |
Hook for saving an image after editing
Is there any hook which is triggered when an image is edited (crop/re-size whatever)? I need to send an email notification to an admin user when an image will be edited (crop/re-size whatever). I need to get media/attachment id as well which have to be sent in email.
I need your advice. | `wp_save_image_editor_file` filter fires after.
add_filter( 'wp_save_image_editor_file', 'custom_wp_save_image_editor_file', 10, 5 );
function custom_wp_save_image_editor_file( $saved, $filename, $image, $mime_type, $post_id ){
//Your logic here
return $saved;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "images"
} |
Need to create a function that will run regardless of W3TC PageCache for every page request
I want to create a specialized function that check certain parameters (page requested, ip of user against a list), if the user matches he will be redirected to a different site, if he doesn't match he will be allowed to continue to the original requested page.
However the website is cached using W3TC Page Cache, and I can't seem to locate the place where I should put my code to act before W3TC returns the cached page. | Since W3TC serves cached pages via htaccess before PHP can do anything, you will have to either:
1. **Do this directly in the .htaccess** file before the W3TC rules.
See for example < although that won't be possible if the list of IPs is dynamic or in a database)
2. **Disable W3 Total Cache's "page cache" but leave other cache types on** (only if you're not on a shared hosting plan and have a VPS or dedicated server)
Don't panic! You'll still get large performance improvements by leaving the "Object Cache" and the "DB Cache" on. Note that these require a memory cache module like APC or xCache installed, which, by the way, I hugely recommend). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "plugin w3 total cache"
} |
How can i summerize posts or news automatically in word press site?
Is there any module or sample code for summerize post by intelligence algorithms?
I want to summerize 1000 last posts automatically | The Summy: Excerpt Extraction WordPress plugin has well documented code to use the Sum+my algorithms.
Instead of looking for a solution that is already used in WordPress, you might find more solutions by searching for PHP solutions that summarize articles and then integrating them into WordPress. WordPress provides a filter that can be used to edit the content for a summary. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, posts, customization"
} |
HM CMB: Role Select
I'm using human made's custom meta boxes framework (< I want to add a select drop down in my metabox wich is populated from the roles on my WP site. How would i populate a select field with the current roles on my site?
I was trying to us a post_select field and WP_Query the roles, but not sure if that's possible:
array(
'id' => $prefix . 'role',
'name' => 'Role',
'type' => 'post_select',
'use_ajax' => false,
'query' => array( 'wp_roles' => array('get_names') )
),
); | There is a list of roles in the `$wp_roles` WordPress global object.
Set `$wp_roles` to a global at the top of your method of function:
global $wp_roles;
Use a Select Field to populate the options:
array(
'id' => $prefix . 'role',
'name' => 'Role',
'type' => 'select',
'use_ajax' => false,
'options' => $wp_roles->get_names(),
),
Note: I didn't install Humanmade CMB to test this code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, metabox, user roles"
} |
Delete all thumbnails for a post
I have a function that sideloads a YouTube thumbnail onto a page... but I want to remove the featured thumb on the page first (and remove all the various auto-generated sizes, too).
I'm assuming I want to use `delete_post_thumbnail()` followed by `wp_delete_attachment()` to un-associated the thumb from the post, and then kill the thumb file. Is that correct? And Will that also delete all the various thumb media files (the extra auto-generated sizes) from the disk? | Using `wp_delete_attachment( $attachmentid, true )` is **only** thing you need.
Passing `true` as second argument, (`$force_delete` see codex ) it:
* remove the thumbnail association with any post
* delete any taxonomy associated to attachment
* and of course remove all the files, also the autogenerated ones
So you do **not** need to also use `delete_post_thumbnail()`. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "post thumbnails, attachments"
} |
Query for draft or scheduled post
What should be the query for checking if there is any draft or scheduled post, I'm not able to make which arguments to take.
Thanks | $draft = wp_count_posts()->draft ? : 0;
$sheduled = wp_count_posts()->future ? : 0;
echo "There are $draft draft posts and $sheduled scheduled posts";
See Codex for wp_count_posts | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "get posts, post status"
} |
echo product-name in a link
I am trying to make a link that links to the wordpress url with the product name after. (<
Here is what I have, I don't know what I am doing wrong.
<?php
apply_filters( 'woocommerce_order_table_product_title', '<a href=" Video'</a>', $item );
?>
Thanks! | I think you're wanting to do this:
add_filter( 'woocommerce_order_table_product_title', 'my_order_table_product_title', 10, 2 );
function my_order_table_product_title( $html, $item ) {
return '<a href="' . urlencode( strtolower( ' . $item['name'] ) ) . '">View Video</a>';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Active menu also for single array
For our (new) website I figured out how to make menu's active. The only problem is that I want multiple pages, singles and categories under one active menu (just to remind people in what section they are).
How do I get this working?
Example: Below the menu gets the status 'active' when viewing the category-app-functies.php.
<ul class="nav navbar-nav">
<li<?php if ( is_category('app-functies')) { echo ' class="current"'; } elseif ( is_singular( 'augmented-reality' )) { echo ' class="current"'; } ?>><a href="<?php echo site_url(); ?>/app-functies/">App Functies</a></li>
</ul>
Also when viewing url.com/app-functies/X/ I like to make the menu active aswell. Is this possible? | Ok, found it out:
<ul class="nav navbar-nav">
<li<?php if ( is_category('app-functies')) { echo ' class="current"'; } elseif ( is_singular( 'augmented-reality' )) { echo ' class="current"'; } ?>><a href="<?php echo site_url(); ?>/app-functies/">App Functies</a></li>
</ul>
If you want to add more then 1 is_category() you can also use `is category('') || is_singular('')` .
Basic PHP knowledge.. but not for a designer like me. Hope this help a lot for other people as well. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
Listing registered scripts
Back story : We have a number of wordpress web sites experiencing issues when viewed on _some_ IE8 browsers. The errors include the page loading but not being displayed (either a blank screen is displayed or the previous page isn't cleared), we think it's down to IE8 and Javascript but want to test that by deregistering each script until 1) it works or 2) we run out of scripts to deregister.
So to the questron : is their an API call that will list the handle of every front end registered script?
I have a back-up of the site's including themes and plugings so I could grep them but I may well miss something and, being lazy, I was hoping I could get wordpress to generate the list for me. | There's a global variable called `$wp_scripts` which is an instance of the `WP_Scripts` class. It doesn't have a public API for looking at registered or enqueued scripts, but you can look inside the object and see what's going on.
You can see all the registered scripts with:
global $wp_scripts;
var_dump( $wp_scripts->registered );
To see the enqueued scripts:
global $wp_scripts;
var_dump( $wp_scripts->queue );
You'll want to run this after all your plugins & theme have had a chance to register their scripts. Maybe as part of a wp_footer handler.
Bear in mind, of course, these are implementation details & not a real API. They could change at any moment in the future. But if you're just debugging for now, you're probably ok. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "front end, debug, scripts"
} |
Error 404 for JQuery import "jquery-1.10.2.min.map"
I got my WordPress 3.6 installation running using a theme I have bought. When I'm using my theme the console says:
GET ...xyz.de/landing/wp-includes/js/jquery/jquery-1.10.2.min.map 404 (Not Found)
This error does not appear when using the default theme. This seems like a broken import of a jQuery file. The site seems to work with the theme enabled. Where should I start looking to fix this in a theme not written by me?
Best regards,
Chris | This is a known issue for WordPress 3.6. There is already a ticket in the WordPress bug tracker. A patch can be found there too but I haven't tried it yet. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes"
} |
WooCommer Product Category Loop - How to change the display order of the rating and price?
I want to do a very very simple thing : To re-order the display of the rating and price information on a WooCommerce product category loop. Now in the product category page I got 5 products, all of the same layout:
\--THUMBNAIL--
| Product name
| Rating
| Price
| Add to Cart
Now I just want to make it like this:
\--THUMBNAIL--
| Product name
| Price
| Rating
| Add to Cart
I know the code just lies somewhere between the hooks; but just cannot find anyway to make it work. If anyone has ever dealt with this problem, please help show me a way to work with this. I would appreciate this very very very much.
Thank you. | For example you just want to swap rating and price where price would come before rating, you would do the following.
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5 );
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 11 );
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 12 );
Put these lines of code in your theme's functions.php file. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, hooks, plugins"
} |
if file_exists not working with wp_enqueue_style
Inside a function I'm doing something like this:
$optional_css_exists = get_template_directory_uri() . "/css/optional.css";
if ( file_exists($optional_css_exists) ) {
wp_enqueue_style('options', get_template_directory_uri() . '/css/optional.css', 'style');
}
But for some reason it's not being enqueued. When I echo out $optional_css_exists, I get the correct path of the file.
If I remove the if statement, the file is enqueued.
Why isn't the file being enqueued when it exists and the path is correct? | URL path can't be passed to `file_exists`
PHP: file_exists - Manual
Use `get_template_directory()` or `get_stylesheet_directory()` instead:
if(file_exists(get_template_directory()./path/file.css'))
as that returns server path | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, css, wp enqueue script"
} |
How to concatenate two separate colums into one?
In phpmyadmin I have two separate columns for latitude and longitude.
e.g. lat: '38.897683' lng:'-77.03649'.
These coordinates are generated for my location custom posts.
How can I automatically merge them into a new (third) column so that I have the values in one string:
'38.897683,-77.03649'.
I would like to apply this to both the preexisting and new posts that are created.
Thaks | Seems like you are looking for a _pure_ SQL solutions for this. You can achieve this by running the following query:
UPDATE wp_posts
SET latitude_longitude = CONCAT(latitude, ", " , longitude);
That will work for you, just double check the name of the columns: `latitude_longitude`, `latitude` and `longitude`.
* * *
**Update**
If you want to run that SQL query each time a post is saved you can use a hook as shown below:
function update_post_location( $post_id ) {
// If this is just a revision, do not update.
if ( ! wp_is_post_revision( $post_id ) )
return;
$query = 'UPDATE wp_posts ' .
'SET latitude_longitude = CONCAT(latitude, ", " , longitude) ' .
'WHERE id = ' . $post_id;
$wpdb->query( $query )
}
add_action( 'save_post', 'update_post_location' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, sql, geo data"
} |
Change a sidebar name?
I'm using a child theme created from a twenty-twelve theme, the theme packs a number of sidebars one which is called "Main Sidebar".
Is it possible to change it's name to something else? | Hook into `register_sidebar` and change the name after the sidebar was registered.
Example:
add_action( 'register_sidebar', function( $sidebar )
{
global $wp_registered_sidebars;
if ( 'Main Sidebar' !== $sidebar[ 'name' ] )
return;
$id = $sidebar[ 'id' ];
$sidebar[ 'name' ] = 'Master';
$wp_registered_sidebars[ $id ] = $sidebar;
});
There is no need to unregister the original if you want to change just the name.
You can change other properties too:
* `description`
* `class`
* `before_widget`, `after_widget`
* `before_title`, `after_title` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "functions, sidebar"
} |
Translating (WooCommerce) placeholder text
So, as the title says, I'm trying to translate the output text of WooCommcerce on the "Cart" and "Checkout" pages, it currently says "select a state" where I want "select a province".
I was not able to accomplish this with filters & hooks, as it's something they have overlooked. I was hoping somebody here can help me figure out how to translate the text so it displays as I want. I don't mind if this is using a plugin, native wordpress functionality or whatever, as long as I get it done.
The site in question can be found here.
Thanks in advance, hopefully you guys and gals can give me a hand with this :)
Cheers, | You can filter `gettext`:
add_filter( 'gettext', function( $translation, $text, $domain )
{
if ( 'woocommerce' === $domain and 'Select a state…' === $text )
return 'Select a province…';
return $translation;
}, 10, 3 );
Note the `3` as last parameter. This ensures you get all three variables passed, so you can replace exactly the text you are looking for. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, plugins"
} |
How to localize data array in plugin's option page
So i am localizing data saved in an array for my plugin's options, however the data is only localized in the front end, how can I localize data in the plugin's option page as well?
The following is what I use to print the data in the front end to be used by my jquery script,
/* localize array data */
$data = get_option('lu_ban_data');
wp_localize_script( 'lu_ban', 'lu_ban_object', $data); | Maybe I am missing the point but assuming that a script is enqueued with the `lu_ban` slug...
function add_data_admin_wpse_112178() {
$data = get_option('lu_ban_data');
wp_localize_script( 'lu_ban', 'lu_ban_object', $data);
}
add_action('admin_enqueue_scripts','add_data_admin_wpse_112178'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, jquery, wp localize script"
} |
Is there a (sane) way to get all custom fields for a post, which do not have a leading underscore?
I know about `get_post_custom()`, but that returns _all_ custom fields, including those with a leading underscore. Is there a reasonable way to get only the ones without a leading underscore? Would I just have to resort to using `get_post_custom()` plus a regex to parse the results? | 1. You can write your own function to do the matching at the SQL level
2. Grab all of the keys and process them in PHP. You shouldn't need regex. Simple string functions should do it.
3. Don't bother processing the results at all and instead just use the keys you need and ignore the rest-- something like `echo $meta['key'];`
4. Just ask for the particular key you want using `get_post_meta`
I doubt that #1 is going to be faster than #2, especially taking into account the built in caching. #3 should perform about as well as #2, given that same built in caching.
I don't know what isn't 'sane' about those options. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
Using wp_handle_upload() to Direct Specific Path by Using $overrides
How do you use `wp_handle_upload` function and `apply_filters` together to upload files on a specific path? What is going to be the override?
**For example:**
$overrides = array('file' => 'C:\\uploads\\filename.pdf','message' => 'File written');
apply_filter('wp_handle_upload',$overrides);
or something like that? Or is this the right code?
**The real question in here is: what`$overrides` can be used as the key to this associative array?** | You need to specify a list of allowed mime types.
You could make it easy by just getting the allowed mime types like:
$file = $_FILES['the-file'];
$upload_file = wp_handle_upload($file, array(
'test_form' => false,
'mimes' => get_allowed_mime_types()
));
If you look at the codex for Default allowed mime types, you could manually specify which ever mime types you want in that format.
An example would be like this answer. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, uploads, hooks, array, wp filesystem"
} |
add oembed provider
I want to add oembed provider to my buddypress activity content
I found this function
<?php wp_oembed_add_provider( $format, $provider, $regex ); ?>
I know I need it to add with `init` filter
I've contacted developers of that site and they gave me oembed link.
so site is <
and they gave me this link: <
so if video is < I need to contact <
But I have no Idea how to sum everything this | The easiest way would be to take advantage of Embedly's outstanding API. Add this code to your theme's functions.php:
// Add Myvideo oEmbed
function add_oembed_myvideo(){
wp_oembed_add_provider(
'
'
);
}
add_action('init', 'add_oembed_myvideo');
Embedly is free up to 5,000 "unique URLs per hour per month". Unless you're going wild with embeds on your site, you'll probably never need to pay. But if you're interested in Embedly's premium services, here's details on their pricing. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "oembed"
} |
Why is this plugin not working?
I am currently learning WordPress Plugin Development. I was trying to insert data into a custom table by means of a plugin. Such that, when an action hook is fired, the data is inserted. It is a pretty simple code here but not getting executed although on debugging I found that the commented echo statement within the function does get executed.
Here is the code -
<?php
/*
Plugin Name: What the wpdb
Description: Making use of wpdb
Version: 1.0
Author: Navin Nagpal
License: GPLv2
*/
add_action('wp_head','nn_do_dbstuff');
function nn_do_dbstuff(){
global $wpdb;
//echo 'Text';
$values = array(
'column1'=>'Navin',
'column2'=>22);
$formats_values = array('%s','%d');
$wpdb->insert($wpdb->custom,$values,$formats_values);
}
?>
My table is named wp_custom and it has three fields including the 'id' field which is the primary key | `$wpdb->custom` should be `"{$wpdb->prefix}custom"`
`$wpdb->insert( $table, $data, $format );` take three params where 1st is table name. you should avoid wp as its not necessary that prefix will always be wp_ instead use `$wpdb->prefix` to get table prefix, `"{$wpdb->prefix}custom"` will output wp_custom (given prefix is wp for your site) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
No responsive design is displayed
I have a strange problem. I'm using the Twenty Thirteen theme. When I decrease the navigator width it should make the h1 title decrease too, but it does not. I have the next default css rule:
.entry-title, .format-chat .entry-title, .format-image .entry-title, .format-gallery .entry-title, .format-video .entry-title {
font-size: 22px;
font-weight: bold;
}
inside
@media (max-width: 643px){ ... }
It works fine with other web page that I've done with the same theme, but not with it. I've tried with different rules, but no luck. When I look at the css code with Firebug, I see the rule, but it is not taken into account in h1 with the .entry-title class. Any idea of what can I be doing wrong? | Well, it was my fault. I had added a media-query to style.css and I put:
@media (min-width: 1300px) {
h2.site-description {
margin-top: 130px;
}
That is to say, I forgot a bracket. It should be:
@media (min-width: 1300px) {
h2.site-description {
margin-top: 130px;
}
}
That broke all my next css properties. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css, responsive, theme twenty thirteen"
} |
Ajax call always returns 0
I have a problem with AJAX returning 0 always!
I have done everything by the book and can't figure out what is wrong? Please help!!
Here is my Ajax call:
//Pass data through AJAX
var amountToConvert = price;
jQuery.ajax({
type:"POST",
url: "../../wp-admin/admin-ajax.php", // our PHP handler file
action: "ajaxConversion",
data: {
amount: amountToConvert
},
success:function(data){
alert(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
And the function in functions.php is:
function ajaxConversion(){
$amount = mysql_real_escape_string($_POST['amount']);
echo $amount;
die();
};
add_action('wp_ajax_nopriv_ajaxConversion', 'ajaxConversion');
add_action('wp_ajax_ajaxConversion', 'ajaxConversion'); | Could you place the action (ajaxConversion) in your Data and check?
jQuery.ajax({
type:"POST",
url: ajaxurl,
data: {
action: "ajaxConversion",
amount: amountToConvert
},
success:function(data){
alert(data);
},
error: function(errorThrown){
alert(errorThrown);
}
}); | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 25,
"tags": "functions, ajax"
} |
Create gallery doesn't show uploaded images
When you do Add Object in a page, for example, a screen is shown where you can see your uploaded images. But it doesn't work for me. No images are shown. What can it be due to? If I open the Multimedia Library the images are there.
If I try to upload an image from this interface (add object) I get an error: There has been an error while uploading. Try again later (not literal, translated from spanish). | I finally found that it is caused from the PHP5.5 version, and it's because of the deprecated function mysql_connect(). I've benn able to solve it by changing the file /wp-includes/wp-db.php (line 1142).
$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
Change with:
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
This makes the gallery to work properly, waiting for the wp compatibility with PHP5.5. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "media library"
} |
How to use get_results() in widget front end?
I'm trying to get_results() in my widget's front end, this is my current code:
public function widget( $args, $instance ) {
echo $args['before_widget'];
if($children = $wpdb->get_results( "SELECT ID FROM $wpdb->posts" ))
echo "working";
echo $args['after_widget'];
}
However I'm getting error "Fatal error: Call to a member function get_results() on a non-object".
I need to access the database to create a menu with the page children. What's am I doing wrong? | It seems that you can't access to it. Please try add `global $wpdb;` to your function.
**UPDATE**
For reference, in WordPress Codex you will find:
> WordPress provides a global variable, $wpdb, which is an instantiation of the class already set up to talk to the WordPress database. Always use the global $wpdb variable. (Remember to globalize $wpdb before using it in any custom functions.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, sql"
} |
Read more to open external link
I would like to have custom field in post editing area where can be putted the external link.
If the link is entered to this field then read more button on homepage would open external link, but if that field is not filled then to use default read more functionality and open a post.
Is there some plugin for this or some hack? | You just need to add `target="_blank"` to the anchor tag.
function remove_more_link_scroll( $link ) {
$link = str_replace('>',' target="_blank">', $link);
return $link;
}
add_filter( 'the_content_more_link', 'remove_more_link_scroll' );
I feel compelled to state that I consider forcing new tabs/windows to be very unfriendly behavior, and if you search the web you will see that I am not alone in that opinion. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, excerpt, read more"
} |
What login/password do I need to install a wordpress theme?
I clicked to download a wordpress theme, and it asked me for user name and password. But I gave it my ftp password and it said invalid. Then I gave it my Wordpress credentials and it said invalid.
So which credentials does it need?
Thank you! | > So which credentials does it need?
If you are able to see the download form, then presumably your WordPress user credentials are OK. So, you need (s)FTP credentials. Either you got the username/password wrong or there is something site specific getting in the way, maybe at the server level. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes"
} |
How to use is_multisite() in a must-use-plugin?
I want this code to be executed in a plugin in the _mu-plugins_ folder. When executing in _functions.php_ everything works fine, but when I try it as a plugin in _mu-plugins_ this creates a blank page.
if (( is_multisite() && !current_user_can('manage_network') ) || ( !is_multisite() && !current_user_can('create_users'))) {
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
} | MU-Plugins load very early-- earlier that your theme or your normal plugins. Because of that, you sometimes need to hook functions that you would otherwise not have to hook.
add_action(
'plugins_loaded',
function () {
if (( is_multisite() && !current_user_can('manage_network') ) || ( !is_multisite() && !current_user_can('create_users'))) {
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
}
}
);
The `plugins_loaded` hook basically means the function will execute just after the normal plugins load, and that seems to be late enough and reasonable to boot. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development"
} |
Filter specific shortcode output?
Is there a hook in WordPress that I can use to filter the output of a specific shortcode? Something like this:
add_filter('shortcode_output', 'my_filter_function', 2);
function my_filter_function ( $output, $shortcode ) {
....
}
Where `$shortcode` would be something like `[my_schortcode]` or even better, shortcode and its attributes separated into an array. | There is no filter that I know of that is meant to target individual shortcodes like you want.
You can filter attributes with `shortcode_atts_{$shortcode}` though.
You can hijack another shortcode by creating your own callback and registering it with the original shortcode slug. I think that is what you are probably going to need to do.
Proof of concept:
function my_gallery_shortcode($atts) {
return 'howdy';
}
add_shortcode('gallery','my_gallery_shortcode');
Now try to use a gallery :) | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 9,
"tags": "filters, shortcode, hooks"
} |
How to redirect specific post type with user role
I have created custom post type `Books` in my `functions.php`. Now I want to redirect every user (assigned with `editor` role). When they click to Dashboard it goes to this page:
What I want:
!enter image description here | add_action('load-index.php', 'redirect_dashboard');
function redirect_dashboard() {
if ( ! is_admin() || current_user_can('activate_plugins') ) return;
$screen = get_current_screen();
if ( is_object($screen) && $screen->base == 'dashboard' ) {
$url = admin_url('edit.php');
wp_safe_redirect( add_query_arg( array('post_type' => 'product'), $url) );
die();
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "user roles, dashboard, user access"
} |
How to change archieve frequency of the media file in uploads folder for wordpress blog
So far I can see my media file is divided into month and year as 2008/09 like directory. But I am getting concerned because I am currently hosting a community listing site that may incurr more than 1000 upload (which is the limit for most shared hosting for EACH directory). I realize recently that the shared site can not have more than 500,000 file/ file in combine. So I think it will be getting pretty limited after a while.
Anyone has solution for this issue in term of changing the archieve frequency maybe into every week instead of every month? I googled it but can never find a answer for it all at! Or...am I getting into a wrong direction?
Please help thank you all! | Assuming you want to set your weekly changing subdirs like, eg '2013/W35' /where 35 stands for 35th week of 2013 (`'W'` param of php date() function),
you can use:
add_filter('upload_dir', 'set_folder_to_week', 999);
function set_folder_to_week ( $upload_data ) {
$y = date('Y');
$w = 'W' . date('W');
$subdir = "/$y/$w";
$dir = $upload_data['basedir'] . $subdir;
$url = $upload_data['baseurl'] . $subdir;
return wp_parse_args(array('path'=>$dir, 'url'=>$url, 'subdir'=>$subdir), $upload_data);
}
All media uploaded before still continue to be founded and displayed correctly by wordpress (if they are retrieved using the proper wp functions).
Note that I've added `'W'` before week number in subdir name to avoid, on the first 12 weeks, url and path are the same of the standard /year/month path. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads, archives, media, hosting"
} |
How much server power does Worldpress take?
I have multiple Wordpress websites on my server(And a game server and Tomcat) and I'm a little paranoid about my servers health. How much does a newly installed Wordpress take typically? | This type of question is open ended to answer because it depends on many variables. The typical memory usage of bare WP usually starts at 15MB and scales up.
What you can do is turn on debugging and install the Debug Bar plugin and it will show you the amount of memory you're using.
In `wp-config.php` set `define( 'WP_DEBUG', true );`
!Debug Bar plugin showing memory usage
Another plugin which shows peak memory usage: TPC Memory Usage | stackexchange-wordpress | {
"answer_score": 5,
"question_score": -2,
"tags": "performance, server"
} |
Carrying information from button click into form
I had a question for a project I am finishing for a client. He would like it so that every time a user clicks on "Sign Up Today" for the given workshop (< the name of the workshop is somehow transferred over the contact form (<
Now the workshop page is just a simple table with a button pointing to the contact us page, and the contact us page is powered by a simple Gravity Forms form.
Is there anyway of doing this either by using Gravity Forms or not? I'm not the best at PHP and have not yet been able to find a way to accomplish this.
Thanks in advance to anyone that can help me out with this. | The better way to do this is using javascript/jquery.
Use either javascript **webstorage api** or jquery ajax **$.post**.
Webstorage api will be good for this.
Here how you can do it.
$('body').on('click', '.button.small', function(){
var index = $(this).parents('table').index('table');
var cur_workshop = $(this).parents('.innercontent').find('h3').eq(index).text();
localStorage.setItem('workshop', cur_workshop);
});
Place above script on < this page template.
Then call the below script on < this page template, to get the current workshop name.
localStorage.getItem('workshop'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, forms, content, plugin gravity forms, table"
} |
How to get comments other than using wp_list_comments?
I'm sure you guys are wondering, "why the hell?" - basically it is because it does not work with a plugin by NextSCRIPTS that pulls comments from facebook. When I'm in the admin panel I see the comments properly, but on the blog posts it just keeps showing the admin instead of the users. This happened after updating to 3.6, NextSCRIPTS told me they are aware of this issue but it has been one month and we have over 8,000 comments and I'd like to find a work around.
So really, you don't need any code from me, just please if anyone knows, can you share how to grab the comments without using wp_list_comments? there has to be another way.
Thanks, Matt | This is going to be a labor intensive workaround but `get_comments` is probably what you want.
From the Codex:
$comments = get_comments('post_id=15');
foreach($comments as $comment) :
echo($comment->comment_author);
endforeach;
There is also `WP_Comment_Query` if you prefer. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments"
} |
get next/previous post name
i know that : `<?php $pagename = get_query_var('name'); ?>` get the name of the current page/post. But I dont know how to get the name of the next and the previous post. I will use it for a hover tip and the alt of the image that will lead to the previous/next post | $prev = get_previous_post();
$next = get_next_post();
$prev_title = $prev ? get_the_title($prev) : 'Current is First Post';
$next_title = $next ? get_the_title($next) : 'Current is Last Post';
See get_previous_post and get_next_post on Codex for some details and additional params you can use. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, pages, previous, next"
} |
The best way to add stylesheets to WordPress
I am in the process of converting a mobile responsive page, currently built in Bootstrap into WordPress.
Using `wp_register_style()` and `wp_enqueue_style()` will add the stylesheets to all pages, including the wp-admin. I know I could get around that by using an `if ( ! is_admin() )` conditional statement.
Is it better to use the conditional statement, or to just to use:
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/bootstrap.css" media="screen" />
in the theme's header.php? | To load scrpits only in front-end pages use:
add_action( 'wp_enqueue_scripts', 'my_front_end_scripts' );
function my_front_end_scripts(){
wp_enqueue_script('script_handle');
wp_enqueue_style('style_handle');
}
To load scripts only in login use:
add_action( 'login_enqueue_scripts', 'my_login_scripts');
function my_login_scripts(){
wp_enqueue_script('script_handle');
wp_enqueue_style('style_handle');
}
To load scripts only in admin use:
add_action('admin_enqueue_scripts','my_admin_scripts');
function my_admin_scripts(){
wp_enqueue_script('script_handle');
wp_enqueue_style('style_handle');
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, wp enqueue style"
} |
Get Attachment Image Class by attachment id
I want Get wordpress media library image class. I have attachment id and I tired this but won't able to get it.
print_r(wp_get_attachment_image_src( $attachment_id, $size, $icon, $attr ));
How can I get it ?!enter image description here | If this is a regular custom field, use `get_post_meta()`:
$classes = get_post_meta( $attachment_id, 'name_of_the_field', TRUE );
`attachment` is just another post type, regarding to meta data, it works like regular posts or pages. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "attachments, images"
} |
Can I explicitly specify ENGINE=InnoDB in Wordpress?
I converted all my tables to InnoDB, but the MySQL server (which I can't access, as I'm on shared hosting) has MyISAM as the default, so every new table that Wordpress creates (e.g. when I add a new site on my multisite) uses the MyISAM engine and I have to alter it manually. Can I somehow set Wordpress up to enforce the InnoDB engine when creating new tables?
I know that by default Wordpress doesn't specify anything and lets the table use the default engine, but I'm wondering if there is some plugin where I could add the
ENGINE=InnoDB
clause to all the `CREATE TABLE` queries. | If the code creating new tables uses `dbDelta()` (it should), you can filter the query (see `wp-admin/includes/upgrade.php`):
add_filter( 'dbdelta_create_queries', function( Array $queries )
{
foreach ( $queries as $table => $query )
{
if ( FALSE !== stripos( $query, 'CREATE TABLE' ) )
{
// change the query here
}
}
return $queries;
}); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugins, database, mysql, innodb"
} |
Order custom Taxomony alphabetically and reversal after clicking a button?
I made a custom type named foods and a taxonomy named fruits. I want to order the fruits name alphabetically ( A-Z ) on clicking a button and then clicking on it again it will show Z-A order.
Can you tell me how to do it please? | Pass order parameter in url on click on link like /?order=DESC or if you are using a button then it must be submitting a form with order field value change GET to POST and field name
if(isset($_GET['order'])){
$order = $_GET['order'];
}
else{
$order = 'ASC';
}
$categories = get_terms( 'category', array(
'orderby' => 'name',
'order'=> $order,
) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "taxonomy"
} |
How to keep sharing stats after creating 301 redirects?
I recently changed a lot of URLs for SEO purposes and realized that all of my Facebook likes and Twitter tweet counts were lost on posts created prior to yesterday. Posts created since yesterday already had SEO-friendly URLs so I didn't have to change them and their social stats are of course, fine.
I used 301 redirects so I can still use the old URL in Facebook and Twitter code since they support indicating another URL to count.I know how to use custom fields in order to fix the old posts, but how do I do this when I have a mix of old posts with new URLs and new posts with unmodified URLs? | Got it.
I was already using the Advanced Custom Fields plugin so I just created a custom field called "old_url" with that.
Then I created a function:
function sharingurl () {
if(get_field('old_url') == "")
{
echo untrailingslashit(get_permalink());
} else {
echo get_field('old_url');
}
}
Then I just included `<?php sharingurl(); ?>` in the data-href and data-counturl for Facebook and Twitter codes respectively.
Note: Facebook does not like trailing slashes, that's why I had to remove it from the permalink. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, redirect, facebook, twitter"
} |
How to remove addthis from my default template
One of biggest mistakes which I committed is that once I installed AddThis plugin and now it appears at the bottom of each page. I removed all the traces of plugin, changed the theme but all in vain. It appears at the bottom above footer in all the pages where I use default template. Please help.
!enter image description here | try grepping your entire wordpress folder for 'addthis'. From your root: `grep -irn "addthis" *`. It's bound to be in there somewhere.
Check in `wp-content`, because you want to search through your themes and plugins. `wp-includes` is part of Wordpress core so I doubt it would contain any references to AddThis. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins"
} |
Why is admin ajax reloading my page
As far as I know I haven't used Ajax anywhere in my code. Yet, while debugging, I have breakpoints being hit with 'admin-ajax.php' at the root of the call stack. This second hit of my breakpoint occurs between 10 and 30 seconds after the original. The weird thing is, as of yet there is no HTML output, so no scripts are present in the browser.
Any ideas why or where this is happening and why my php scripts are being called twice? | This is probably the new Heartbeat API. It is running in intervals from 15 to 60 seconds and offers a simple way to communicate with WordPress per AJAX in the background.
You can disable it in JavaScript with `wp.heartbeat.stop();` and in PHP with `remove_action( 'admin_init', 'wp_auth_check_load' );` (might not be enough on some pages). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "ajax, debug"
} |
Should I use include or load_template for including shortcodes, plugins and so on?
I am wondering what is the right way to include additional php files for theme options, shortcodes, plugins and so on.
Both load_template and include will work, but what has better semantic value?
Thanks | `load_template()` is for cases where you need the following global variables in an included file:
$posts,
$post,
$wp_did_header,
$wp_query,
$wp_rewrite,
$wpdb,
$wp_version,
$wp,
$id,
$comment,
$user_ID
If you don’t need those, or if you use `global` in those files anyway, it isn’t needed.
`locate_template()` and `get_template_part()` are for cases when you want to allow child themes to replace the files with their own version. If you offer other ways to turn the loading off, it isn’t needed.
So, it depends on the context, on the position of your theme in the hierarchy (parent or child), and on the included code. You can use `require` if you want to. Avoid `require_once` and `include_once`, they are more expensive.
And shortcodes are not part of a good theme. :) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, functions, include"
} |
help me about my slide bar
i my website them has a sildeshow in this slideshow show 5 newsest post! i need chane newpost to a Specific catagory for exp news catagory? my slideshow code is:
<div class="callbacks_container">
<ul class="rslides" id="slider3">
<?php
$the_query = new WP_Query(array('order' =>'descending','orderby' =>'ID','posts_per_page' =>'5'));
while ($the_query->have_posts()) : $the_query->the_post(); ?>
<li>
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail('large');
}
else {
echo '<img alt="No Image" src="' . get_stylesheet_directory_uri() . '/images/no-image.png" />';
}
?>
<p class="caption">
<?php the_title(); ?>
</p>
</li>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul>
</div>
plz help me soon!
tnx alot | As far as i understand your question is that you want to get posts from specific category.
<div class="callbacks_container">
<ul class="rslides" id="slider3">
<?php
$the_query = new WP_Query(array('order' =>'descending','orderby' =>'ID','posts_per_page' =>'5', 'category_name' => 'news'));
while ($the_query->have_posts()) : $the_query->the_post(); ?>
<li>
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail('large');
}
else {
echo '<img alt="No Image" src="' . get_stylesheet_directory_uri() . '/images/no-image.png" />';
}
?>
<p class="caption">
<?php the_title(); ?>
</p>
</li>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul>
</div>
Add **category_name** to the $the_query array and give the value of your category slug.
Like this:
'category_name' => 'news' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "slideshow"
} |
Custom user roles for access to specific parts of the site
I need to create specific sections of my site which should only allow certain users to access them.
So basically, I'll be having a staff section - if the user is a staff member, they'll see a link to the section and obviously be able to see all the info there.
I've looked into a couple of things, namely adding user roles but they all seem to have a set list of capabilities that I can set. There isn't anything that I can find that will allow me to restrict users access to certain parts of the site.
I don't mind using plugins or anything like that - any suggestions would be welcome. | You could create a new role, say `staff`, and add the users you want to that specific role. Then link that role a new capability of your choice, e.g. `access_staff`.
Now you have a new role with a new capability, so all you need to do to restrict the access to any part of the site is add this piece of code:
if ( is_user_logged_in() && current_user_can( 'access_staff' ) ) {
// Section
} else {
// Let them know they don't have enough privileges or...
wp_redirect( wp_login_url( get_permalink() ) ); // Send them to the login page
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "user roles, capabilities"
} |
order users with drag'n'drop?
There are many plugins out there that let you order Pages and/or Posts with drag and drop.
Is there something similar to order users?
Or if not, is it possible to create a plugin for that (i.e. are there sufficient filters, actions etc. in place? | It seems there is no such plugin...
So I created my own: <
(~300 php lines, too long to post here)
Influenced a lot by "Simple Page Ordering" plugin, but created from scratch.
The lousy truth about this problem is that there seems to be no built-in way to sort users by meta-value. Luckily I have only 10-20 users so hopefully it won't be too performance-expensive to sort them manually after fetching (that means one additional query per user to fetch meta value). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "users, order"
} |
Turn Current Date in Custom Field Ouput Green or Red
Using a custom field of "Due" how would I change the current date to green or red depending on if it has expired or not? Could someone point me in the right direction? My meta key is simply "Due"... | Changing the text/background colour is easy W3 Schools. You can do this with javascript or easier just add a style to the `<div>` with a PHP condintion
<?php
if ( $due == true )
echo '<div style="color: red">';
else
echo '<div style="color: black">';
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field"
} |
Hide metabox dependant on page template chosen
I'm using the following JQuery script from this answer to toggle the display of metaboxes dependant on the Page Template selected. The example below shows the **featured image** metabox when the **default** template is selected:
(function($){
$(function() {
$('#page_template').change(function() {
$('#postimagediv').toggle($(this).val() == 'default');
}).change();
});
})(jQuery);
My possibly simple question is... How do I get this code to only show the featured image box for my Page Template entitled: **Services**?
I have tried simply changing the `'default'` to '`Services'` but no luck. | The `value` is not the same thing that you see when you look at the toggle. That part is for humans. To see the value you have to look at the source of the page. If you have a template created by `template.contact.php` the `value` in that box would be `template.contact.php`, so it looks like the `value` is the `php` file name. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "jquery, admin, metabox, wp admin"
} |
Show wordpress locally in xammp and in iPhone via ip
My wordpress site works fine on my mac via localhost, using Xammp. I want to view the site on my iPhone. So I type in 192.168.0.2 and voila, it brings up my localhost directory. I then click on the site in question and the content is there but no styling or images. I realise that this is because the paths to all the resources is hardcoded into the wordpress database. So when I am accessing the url via 192.168.0.2/mywebsitename on my iPhone, it's looking for all the resources using a base url of localhost/mywebsitename. Localhost path doesn't exist on my iPhone, only 192.168.0.2 does.
So has anyone found a solution to this little issue? How can I see a wordpress installation by ip address and by localhost access? | You can adapt the site url which is stored in the database based on what domain you are viewing the site from. Add the following to `wp-config.php`:
define( 'WP_HOME', ' . $_SERVER['HTTP_HOST'] . '/yourwebsitename' );
define( 'WP_SITEURL', WP_HOME );
If you use a subdirectory install (ie: you view the site from ` but the WordPress core files are stored in ` (or similar), you will need to add this to the second line:
define( 'WP_SITEURL', WP_HOME . '/wp' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "apache, configuration"
} |
How can I make my blog urls have words of the title in them?
I just started a new blog and all the urls look like this:
sitename.com/?p=1
But how do people make the url have the title of the blog
Thanks! | From the WordPress Codex, this is how to enable permalinks in your blog. From your admin dashboard on the left side go to Settings -> Permalinks
> In the Settings → Permalinks panel (Options → Permalinks before WordPress 2.5), you can choose one of the "common" structures or enter your own in the "Custom structure" field using the structure tags.
>
> Please note: You never, ever put your site url in the permalinks slot. You must use one of the structure tags, or a combination of tags only.
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "urls"
} |
force http canonical tag on https pages
At present all https pages have their own canonical tags referencing https, which is incorrect, they should be referencing the http versions.
e.g:
has the following canonical tag:
`<link rel='canonical' href=' />`
How can we make the canonical tags on https pages use the http URLs? | You can change it using following code, add it in your theme function.php or in plugin.
remove_action ( 'wp_head' , 'rel_canonical' ) ;
add_action ( 'wp_head' , 'my_rel_canonical' ) ;
function my_rel_canonical () {
ob_start () ;
rel_canonical () ;
$rel_content = ob_get_contents () ;
ob_end_clean () ;
echo str_replace ( "https:" , "http:" , $rel_content ) ;
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "duplicates, https, http"
} |
users and usermeta table
Is it mandatory for each user to have entries in usermeta table as well or it's optional? Recently, I came across a wordpress database which has thousands of users in user table however only a few of them have entries in usermeta table.
I am wondering in what scenario this could have happened as it doesn't look like those entries were manually removed from database. | install a fresh wordpress setup on your local machine and then have a look at `wp_usersmeta table .` It contains meta(additional) information for each user.You (admin) can also make data entry specific to any user by this function `update_user_meta()` in usermeta table. and retrive the same using `get_user_meta()` funciton.
All fields for all users are not necessary. meta keys can be user specific also.
defaults meta key entries for admin in wordpress 3.6 --
first_name
last_name
nickname
description
rich_editing
comment_shortcuts
admin_color
use_ssl
show_admin_bar_front
wp_capabilities
wp_user_level
dismissed_wp_pointers
show_welcome_panel
wp_dashboard_quick_press_last_post_id
managenav-menuscolumnshidden
metaboxhidden_nav-menus
nav_menu_recently_edited
closedpostboxes_page
metaboxhidden_page
metaboxhidden_page
wp_user-settings wp_user-settings-time | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "users, user meta"
} |
Problem in register activation hook and Copying folder
Hy Guys, I am wanting to copy a folder to activate my plugin, I'm trying this but it does not work.
function hyperbolic_activate() {
$src = 'includes/myTheme/';
$dst = '../themes/';
function recurs_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
} else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
}
register_activation_hook( __FILE__, 'hyperbolic_activate' );
What is the problem in my code? | You are defining the recurs_copy() function to perform the copy but you never execute it. Try:
function hyperbolic_activate() {
$src = 'includes/myTheme/';
$dst = '../themes/';
recurs_copy($src, $dst);
}
register_activation_hook( __FILE__, 'hyperbolic_activate' );
function recurs_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
} else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "hooks, user registration"
} |
Run "get_the_post_thumbnail" with a different table prefix?
I have this site were I run two Wordpress sites on the same database (with different prefixes), on one domain.
What I want is to get the post thumbnail from the second Wordpress installation, by running the function `get_the_post_thumbnail` (with a different table prefix), on the first Wordpress installation.
Simplified:
Two Wordpress sites, One database, Wordpress site "a" want to get a post thumbnail from Wordpress site "b" through the function `get_the_post_thumbnail`
I really hope this makes sense! | Why didn't you use a Network/Multisite install? Problem mainly is that all the queries normally have the current install prefix in use. Without having real access (via `$wpdb`) to the prefix, this will get pretty messy. Actually your problem is a X-Y Problem.
It would be less work to export everything from one of the sites, quickly convert the other site to multisite and then import the data again. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, wpdb"
} |
Wordpress link to show popup box
I have a button on my wordpress page that is wrapped in tags. Can I edit the link so that when someone clicks on it, it just shows them a popup message box, and stays on the page that they were on?
Thanks!
Sample code:
<a title="My Title" href="www.website.com/we-should-change-this-url"><img class="alignleft wp-image-652" alt="ITIN2" src="www.website.com/image-url" width="220" height="55" /></a> | There is more to it do you think but here's a simple popup message sample I've created.
Have a look at it and let me know if you need further help.
**For future reference:** This sort of question should be asked at Stack Overflow! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "links"
} |
Rewrite category list as an if / else statement
I have written this script to list the neighborhood associated with a post:
<div class="neighborhood">What's Happening in:<?php
foreach((get_the_category()) as $childcat) {
if (cat_is_ancestor_of(12, $childcat)) {
echo '<a href="'.get_category_link($childcat->cat_ID).'">';
echo $childcat->cat_name . '</a>';
}}
?></div>
It works great. But I need to rewrite this to be an if / else statement, in the event that there is no neighborhood assigned to a post that the "What's Happening In" part would not appear.
My PHP isn't super strong, and I'm not sure how to restructure the code so that it is an effective if / else. Any help is appreciated. | See the comments in code for explaination
// all the categories for the post
$categories = get_the_category();
// extracts ids form post categories
$categories_ids = wp_list_pluck( $categories, 'term_id' );
// all the categories id that are descendant of category 12
$children = get_terms('category', array('child_of'=>12, 'fields'=>'ids') );
// all the categories id for the post that are descendant of category 12
$neighborhood = array_intersect($categories_ids, $children);
// show the div only if we have neighborhood
if ( ! empty($neighborhood) ) {
echo '<div class="neighborhood">What's Happening in:';
foreach ( $categories as $cat ) {
if ( ! in_array($cat->term_id, $neighborhood) ) continue;
echo '<a href="'. get_category_link($cat->term_id) . '">' . $cat->name . '</a>';
}
echo '</div>';
}
More on:
* wp_list_pluck
* get_terms
* array_intersect | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
How to force content refresh of a page that has been loaded previously by the user?
How can any page on the site be forced to refresh or load content by ignoring anything in cache, everytime a visitor visits the page for the second time? The website uses twentyeleven & w3tc (browser caching disabled at the moment). | Since, your site already uses W3 Total Cache plugin, let me provide a solution based on it.
Please visit yoursite's wp-admin/admin.php?page=w3tc_browsercache and look for the text "Set cache control header". Check this option, if it is unchecked, and then choose "no-cache" for the "Cache control policy". This needs to be done in three places...
1. CSS & JS
2. HTML & XML
3. Media & Other files
!enter image description here
If you do not wish to use W3 Total Cache plugin for some reason, you may set the following in 'htaccess' file or in Apache configuration, assuming your server has mod_headers module...
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate" | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "cache, plugin w3 total cache, theme twenty eleven"
} |
Site Crashes When Updating to WordPress (Version 3.6)
I was just clicking the update button behind in the admin panel. it said no enough space in my hosting. then i went and removed some files and tried again then it was processing the wp update. suddenly it took me to a blank page and now the entire site looks empty.
I am guessing this could be due to space limitation in hosting account. even though i removed a few and tried updating, it might have meet not enough space in the middle of updating and its leading to this issue.
Also in the mean time i tried accessing this page: `www.mywebsite.com/wp-admin/update-core.php` and got the below error.
> Fatal error: Call to undefined function nocache_headers() in /home/webmas8/public_html/azraar/wp-admin/admin.php on line 32
This is the website that causes the issue: < | Probably the update wasn't complete and some files are missing.
If you have FTP access, follow these steps.
1. Download you `wp-config.php` and save it somewhere.
2. In the wp folder on server delete everything **but** the wp-content folder
3. Have a DB backup, if you can
4. Download from wordpress.org the zip of wordpress and extract it
5. At this moment remove the `wp-content` folder from the extracted zip
6. Also remove the `wp-config-sample.php` and put there your `wp-config.php`
7. Via FTP, upload to server all the files
Now it should work, but probably you have to change hosting... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, updates, automatic updates, fatal error"
} |
How come my first blog post and my home page have the same title?
I am putting together a new blog and for some reason the home page took the title and description of the initial post. Is there a way to just set the home page title/description separately?
I am trying to edit it via YoastSEO, but I get this screen when I try to set my Home title/description:
!enter image description here
But what I was expecting was the form fields for title/description.
Thank you! | The "Reading Settings" at a domain's wp-admin/options-reading.php is, by default, set to latest posts. So, WordPress, by default, would show the title of the post being set at "General Settings" at a domain's wp-admin/options-general.php . In this case, Yoast's WordPress SEO plugin would have form fields to customize it.
When the "Reading Settings" are changed to show a static page as the front page, then the title of that page is shown as the title of the blog itself. This is the expected default behavior. Yoast's WordPress SEO plugin would have not any form fields, in this case, but would contain the link to the post to edit the title and the description. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "title, description"
} |
How to use author id in post permalink
Currently, Wordpress supports author name in the post permalink by using %author%.
Is it possible to add the author id to the permalink?
For example, changing this:
<
to this:
<
Where '1' is the id of the author 'john'. | You can do this with a couple of filters:
<?php
function wpse_112719_pre_post_link( $permalink, $post, $leavename ) {
if ( strpos( $permalink, '%author%' ) !== false ) {
$authordata = get_userdata( $post->post_author );
$author_id = $authordata->ID;
$permalink = str_replace( '%author%', $author_id, $permalink );
}
return $permalink;
}
add_filter( 'pre_post_link', 'wpse_112719_pre_post_link', 10, 3 );
function wpse_112730_add_rewrite_rules() {
add_rewrite_rule(
"([0-9]+)/(.*)",
'index.php?name=$matches[2]',
'top'
);
}
add_action( 'init', 'wpse_112730_add_rewrite_rules' );
Now, go to Settings -> Permalinks and set your permalinks settings to `/%author%/%postname%/`. Save your changes, and your links should be working accordingly. Let me know if you have any issues! | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "permalinks"
} |
Why doesn't YoastSEO allow me to set the title/description for the home page?
For some reason, YoastSEO set my home page to the first blog post. So the home page canonical, title, and description are set to the values of the first blog post.
And when I tried to set the home page's title/description, I got this screen instead of the form fields to set the values of the title/description:
!enter image description here | Check Settings > Reading. If you have a Posts/Front page page set, you'll need to add the meta title/description on those particular pages. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "title, plugin wp seo yoast, description"
} |
Can Settings API setting generate other settings?
I have a Settings API field for an address. The address is stored this form: "Address, City, Country".
Is there any way of creating / generating other options based on the one above? When I save the option I want it to generate and save latitude and longitude variables because I need them in order to display the address on the front-end (Google Map)?
Any ideas how to resolve that? I could do that on front-end but then I will have to request the data for every user, not only once and I don't want to do that (performance & there's 25k/monthly limit of requests). I don't want to create additional Settings API fields neither. | I believe you should be able to use the `update_option_{$option}` hook:
do_action( "update_option_{$option}", $oldvalue, $_newvalue );
Something like:
add_action(
"update_option_youroptionname",
function ($oldvalue, $_newvalue) {
// process your option value and update/insert options as needed
// var_dump($oldvalue, $_newvalue); // debug
// wp_die(); // debug
},
1,2
);
Be sure to replace "youroptionname" with the appropriate value. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme options, settings api"
} |
When adding a widget, what kind of widget should I used to add images and text and styling?
Is there such a thing? I would settle for images, text and maybe headers.
I know I can add HTML into the text widget. So is that what I should be doing? But how do I add images to the site? That widget doesn't have the image upload option.
Thanks! | The only out-of-the-box solution is to use the text widget and hand-code your HTML and images.
However, there are plugins, this is one I use. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "widgets, widget text"
} |
WPML Get url without outputting
I am in the process of migrating from qTranslate to WPML to handle my languages.
With qTranslate, I had a very simple way to get an url to a page or post knowing it's slug: `$url = get_language_url(home_url($slug));`
Now with WPML I can't find a way to do that...
There's the `icl_link_to_element` function but it directly outputs the link in a a tag.. Besides, you need to know the post ID.
Any way I can get a link to a post in the correct language, knowing it's slug? | Actually Wordpress lacks a real function to get posts by slug/post-name. But you can use get_page_by_path() for it so you don't have to use a custom query:
if(function_exists('icl_object_id')) {
$post = get_page_by_path('your-slug');
$id = icl_object_id($post->ID,'post',true);
$link = get_permalink($id);
}
The only difference here is that you must use the full path i.e. (`'parent-page/sub-page'`) if you have a hierarchical structure. For posts and non-hierarchical pages you can just use the slug as param. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "urls, multi language, plugin wpml"
} |
Modify the main loop to display current month / year
So `pre_get_posts` seems to be the way to do this now - a lot of the background is nicely explained here: When to use WP_query(), query_posts() and pre_get_posts
I can happily modify the main loop to show a chosen month using this function:
function loop_current_month( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'monthnum', 3 );
return;
}
}
add_action( 'pre_get_posts', 'loop_current_month' );
However, I would like to modify the loop for the current month, and the current year.
How can `$query->set()` take two vars? Something like:
$query->set( 'monthnum', 3 & 'year', 2013 );
Any ideas?
Many thanks Dave | have you tried adding a second $query->set() ?
function loop_current_month( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'monthnum', date('m') );
$query->set( 'year', date("Y") );
}
}
add_action( 'pre_get_posts', 'loop_current_month' );
This should get all the posts from the current month or this year, note date('m') and date('Y') | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "loop, pre get posts"
} |
How to order users alphabetically by their last name?
I use the following shortcode and function to display members of some departments:
add_shortcode( 'list_of_members', 'members_listing' );
/* usage: [list_of_members department = 'psychology'] */
function members_listing( $department ) {
$members = get_users( array( 'meta_key' => 'department', 'meta_value' => $department ) );
echo '<ul>';
foreach ( $members as $member ) {
echo '<li>' . $member->first_name . ' ' . $member->last_name . '</li>';
}
echo '</ul>';
}
I'd like to order the users alphabetically by `last_name`. How can I do this?
I was inspired by this question/answer, but I do not understand it completely. | Why don't use built-in functionality of PHP?
Put the following line right before the `foreach`:
usort($members, create_function('$a, $b', 'return strnatcasecmp($a->last_name, $b->last_name);'));
**References:**
* `usort`
* `create_function`
* `strnatcasecmp` | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "users, user meta, sort, order"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.