INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Randomize Users
I'm trying to randomly display my users and I was wondering if I could edit the answer on this page to suit my needs (multiple users instead of a single user): Sidebar random author spotlight
Here's my code (I can easily switch to `WP_user_query` if need be)
<?php
$args = array(
'fields' => 'all_with_meta',
'exclude' => array(1),
);
$users = get_users( $args );
foreach( $users as $user ) { ?> | I don't see an "orderby Rand()" parameter for either `get_users` or `WP_User_Query`. There is a filter called `pre_user_query` that could be used but I am not sure I see the benefit of that when `shuffle` will randomize the array you already have.
$args = array(
'fields' => 'all_with_meta',
'exclude' => array(1),
);
$users = get_users( $args );
shuffle($users);
var_dump($users); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "user meta, users, wp user query"
} |
Fancybox plugin: triggering on href attribute
I want to show a pop up when clicking on an anchor with a specific url. I've tried the following code in the extra calls tab but it doesn't work.
jQuery("a[href='
'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200, 'type': 'iframe', 'height': 800 });
I assume the problem is in the selector since I have another script where the code beyond the selector is identical to the above, and it works perfectly. I tested the syntax of the selector at W3 schools doing a simple add class test and the syntax appears to be correct.
Any suggestions as to the source of the problem? Syntax, perhaps Fancybox has trouble with certain selectors?
Any advice would be appreciated.
Thanks. | jQuery('a[href^="
Try this.
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery('a[href="
'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200, 'type': 'iframe', 'height': 800 });
});
</script>
I checked on my DEMO, and it works for me
Make sure your site already load jQuery : if there is no jquery.js loaded, use the following code to load
<?php wp_enqueue_script('jquery');?>
add the above code before `<?php wp_head(); ?>` in header.php // | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Auto approve all comments (editor)
I **unchecked** both options in the `discussion` area _(so the one where they need a post to comment and administrator has to approve)_ , but still, my users can't put their comments without me approving it.
Has someone a solution for this glitch? Why on earth can't they post a comment? And if they post one, the second one needs to be approved? | I used `multiple links` in a `comment` and I saw that there was an option to avoid comments that have more links than 2 in _(moderate comments)_. I set it to 0 and now it works like a charm.
Wordpress, oh Wordpress! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, author, editor, options, comments template"
} |
how do I get the tag name from tag id?
I have the tag ID, in integer format.
I want to convert this to the tag name. e.g. "cars"
How do I do this? | Use `get_tag`.
$tag = get_tag(2); // <-- your tag ID
echo $tag->name; | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 5,
"tags": "tags"
} |
remove "index.php" from permalinks
I have been trying to find a solution. but I can't..
my links are all `domain.com/index.php/post_name/`
I really want to remove `/index.php`
I have searched and found some... saying I need to add these.. but it's not working ..
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
I am using 3.5.2 wp.
Please let me know if you know anything about it. | Go to your WP-ADMIN-->Settings-->Permalink and use the permalink structure change there, if it generate any `.htaccess` file copy the content and update your `.htaccess` file.
Or Check if your hosting `mod_rewrite` is enable by creating a file `phpinfo.php` with content,
<?php phpinfo();?>
Upload this file and browse via Browser. So you know which modules are enabled. You need mod_rewrite enable to remove `index.php` from URL.
More details Check this link | stackexchange-wordpress | {
"answer_score": 24,
"question_score": 27,
"tags": "permalinks, url rewriting, urls, rewrite rules, mod rewrite"
} |
While loop articles - if statement order
I want to show a list of articles, but I want to show in the 1st place my second article and after it the last.
_Eg: Article 1 Article 2 Article 3 Article 4 to be: Article 2 Article 1 Article 3 Article 4_
I'm using this while loop:
<?php
$i = 0;
$the_query = new WP_Query( 'showposts=35&offset=0' );
while ($the_query -> have_posts()) : $the_query -> the_post();
$i++;
if ($i==2) {
echo 'Article2: '.the_title();
}
if ($i==1) {
echo 'Article1: '.the_title();
}
endwhile;
?>
But It render: Article1 Article2
I want to render this: Article2 Article1
Thank you in advance!
PS: I want to do this because I want different positions of articles (like CNN) and I don't want to repeat WP_query for all my 34 articles on homepage... Because of this i use if statement.
If you think that this is not a good question please do not -1 me, I will delete my post if you want. | Prepare the query before you loop over it:
$first = array_shift( $the_query->posts );
$second = array_shift( $the_query->posts );
// now re-add in reverse order
array_unshift( $the_query->posts, $first );
array_unshift( $the_query->posts, $second ); // this is now the first item
while ($the_query -> have_posts()) : $the_query -> the_post(); // regular loop | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, query posts, get posts, order"
} |
How do I add Javascript and CSS files into WordPress?
I have the following html code:
<script src="js/jquery.vmap.js"></script>
<script src="js/jquery.vmap.world.js"></script>
<script src="js/jquery.vmap.sampledata.js"></script>
<script>
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: null,
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
values: sample_data,
scaleColors: ['#C8EEFF', '#006491'],
normalizeFunction: 'polynomial'
});
</script>
<div id="vmap" style="width: 600px; height: 400px;"></div>
How can I add the used Javascript (or CSS) file into my new page ? Do I have to copy and paste the files through FTP ? | For your purpose _enqueue_ is the key:
* `wp_enqueue_script()`
* `wp_enqueue_style()`
You can consult this question: **How to enqueue the style using wp_enqueue_style()** for style enqueue.
For scripts enqueue I recently did as:
// ENQUEUE JAVASCRIPTS FOR CUSTOM PURPOSE
function scripts_for_something() {
wp_register_script( 'my-scripts', get_template_directory_uri() . '/js/my-scripts.js' );
wp_enqueue_script( 'my-scripts' );
}
add_action( 'admin_enqueue_scripts', 'scripts_for_something' );
`admin_enqueue_scripts` will enqueue the scripts in the admin panels only. You can use `wp_enqueue_scripts` instead for front-end. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "jquery, css"
} |
Dynamic image crop in WP 3.0+?
Since WP 3.0 does not support hard crop anymore (the only way to crop is in media manager), how am I suppose to dynamically crop my thumbnails? I don't want to crop them manually one by one... | <
<
$image = wp_get_image_editor( 'cool_image.jpg' );
if ( ! is_wp_error( $image ) ) {
$image->rotate( 90 );
$image->resize( 300, 300, true );
$image->save( 'cool_image.jpg' );
}
Repalce cool_image.jpg with a variable holding the path to the image you want to edit. Not a copy and paste solution but should put u on the right track. There is a crop function.
crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false );
//Crops Image. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "images, thumbnails"
} |
Make title field multiline in the add new custom post page?
I have a custom post type named "news". The title field holds the raw news and i added another custom field that holds the published news. The published news field is a text area so i can use enter button when editing. Is there a way to make the title field behave like that, to edit in multiline?
thanks | You shouldn't really be using the title for chunks of content. That title is used for things like generating `URL`s, for example, and it could be used for all kinds of things by the theme and plugins. That is almost certainly going to cause trouble.
I'd suggest you register your post type without 'title' support and create a custom meta box for you "raw news", or just use the title for it is meant for-- a title.
To answer the question directly though, the markup that generates the title section is hard-coded. You can't alter it.
# Related:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, customization"
} |
Publish and save specific postmeta to a filtered post_type
I have multiple plugins with different post_type(s). When I save or publish, all of the `custom_post_meta` that belong to one specific `post_type` are also saving.
I'd like to filter by `post_type` so that the `custom_post_meta` will only save in a specific `post_type`.
So my question is, if you have multiple plugins:
**How do you save a specific postmeta** to a specific `post_type`?
Would you just say:
if (post_type=="my_post_type") {
add_action('save_post','save_my_meta_box_to_postmeta');
add_action('publish_post','save_my_meta_box_to_postmeta');
}
And how do you **get** the `post_type` value? | Do the check inside the callback. `save_post` will pass you both the post ID and the post object:
do_action('save_post', $post_ID, $post);
So...
function save_my_meta_box_to_postmeta($post_ID, $post) {
if ('yourtype' === $post->post_type) {
echo '<pre>';
var_dump($post_ID,$post);
echo '</pre>';
die;
}
}
add_action('save_post','save_my_meta_box_to_postmeta',1,2);
You may want other conditionals as well like `!DOING_AJAX`, for example. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, post meta"
} |
Adding line breaks to nav menu items
I need to add line breaks to the nav menu item titles. I didn't realize this was a problem as when I am logged in as a Super Admin, I can add `<br/>` just fine, but apparently regular-level admins cannot.
I've read over this post Custom Menus Description Stripping HTML Tags
but I'm fairly convinced the tags are being stripped on on save/update, so I am not immediately seeing how a Custom Walker is the solution, but my brain is pretty well shot today, so it might be obvious.
There also doesn't seem to be any sanitation happening in `wp_save_nav_menu_items()` or `wp_update_nav_menu_item()`. | Following the hint from @Rarst regarding safe characters here's what I ended up doing:
function wpa_105883_menu_title_markup( $title, $id ){
if ( is_nav_menu_item ( $id ) && ! is_admin() ){
$title = preg_replace( '/#BR#/', '<br/>', $title );
}
return $title;
}
add_filter( 'the_title', 'wpa_105883_menu_title_markup', 10, 2 );
**Edit** : Also per Rarst's comment I've replaced the `preg_replace` with `str_ireplace`
function wpa_105883_menu_title_markup( $title, $id ){
if ( is_nav_menu_item ( $id ) ){
$title = str_ireplace( "#BR#", "<br/>", $title );
}
return $title;
}
add_filter( 'the_title', 'wpa_105883_menu_title_markup', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 8,
"tags": "menus"
} |
Trigger a function during onload
I recently added Javascript and CSS files into the wordpress. All the files are being registered through `functions.php`. One of the files is `my_worldmap.js` as shown below
$(function() {
$('#world-map').vectorMap();
});
The issue here, the above function is called as soon as I visit the homepage. My expectation that the code is only called when I visit `www.mydomain.com/global-network`. How can I do this in WordPress ? | Enqueue your script only when the page you want it on is requested:
function wpa_script() {
if( is_page( 'global-network' ) ){
wp_enqueue_script(
'wpa_script',
get_template_directory_uri() . '/js/my_worldmap.js',
array('jquery')
);
}
}
add_action( 'wp_enqueue_scripts', 'wpa_script' );
See `is_page()` in Codex. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
} |
Embedding Youtube video on comments
In my posts, you can embed a video of Youtube by adding the link to the post. You don't have to do anything beside that.
On my comments, I can't do the same thing. Is it possible to embed Youtube video's by putting the link only (or a different manner, but I prefer the first), and if so, how? | Just add the comments to oEmbed. Here's a small plugin that you can use as MU-Plugin or normal plugin and that should explain what's going on pretty well.
<?php
defined( 'ABSPATH' ) or exit;
/* Plugin Name: (#105942) oEmbed Comments */
add_filter( 'comment_text', 'wpse_105942_oembed_comments', 0 );
function wpse_105942_oembed_comments( $comment )
{
add_filter( 'embed_oembed_discover', '__return_false', 999 );
$comment = $GLOBALS['wp_embed']->autoembed( $comment );
remove_filter( 'embed_oembed_discover', '__return_false', 999 );
return $comment;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "embed, youtube, comments, comments template"
} |
Infinite Scroll plugin scrolling truly "infinitely" (i.e. does not recognize end of posts)
I'm using the infinite scroll plugin and on some pages it just scrolls forever and is not showing the _"No more posts to load"_ message.
Happens with newest WordPress version and also with the twentyeleven theme.
Anybody knows this problem?
How can I make this work? | I think I already had this problem some month ago.
It may help you to add the following code to your themes functions.php: <
The problem in this case was actually located in a wp core function (redirect_canonical() in wp-includes/canonical.php) which tries to "repair" broken/malformed url's instead of showing an 404 error and ist not behaving in a constant way. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Where to add the code for an outer container in a theme?
I have a Wordpress theme installed (SimplePress) and I would like to add an outer container to it, and I don't know exactly in which file should I add the code.
This is the code I tried to use:
<div id="hbz_outer_container" style="position: relative;">
<div id="hbz_drop_shadow">
This is an example of how I would like it to look: <
I tried adding the code to some of the files, like `scripts.php` or other files from the theme, but I don't know if I have to change a file from the theme, or a file from WordPress. | It is really hard to say without being able to look at your theme files directly. But you are most likely going to have to put
<div id="hbz_outer_container" style="position: relative;">
<div id="hbz_drop_shadow">
somewhere in your header.php and then put the closing tags:
</div><!-- hbz_drop_shadow -->
</div><!-- hbz_outer_container -->
in your footer.php
header.php and footer.php should be located in your wordpress installed themes folder.
ie:
yoursite/wordpress/wp-content/themes/header.php
and
yoursite/wordpress/wp-content/themes/footer.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "theme options, id, css"
} |
User profile update author
So I'm trying to create email notifications to certain users to update them on updates to user profiles. I'd like to send these users the profiles that were updated, and also which user made these updates. Sometimes administrator-level users may make changes to other user profiles. I know I can hook into the profile_update to send emails when an profile is updated, but the big question is how to get information on who made these profile updates?
Any suggestions on how to do this would be appreciated.
Thank you | `wp_get_current_user` used inside your hook callback should tell you who is making the edit.
$editing_user = wp_get_current_user();
Without code, that is all I've got. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "email, profiles, notifications"
} |
How do I add JavaScript that will execute on all my sites in Multisite?
We are creating an internal network of sites using MU and there are some small things we would like to have globally on all the sites without having to add them individually for each site. I would like to add a block of JavaScript and CSS that will execute on every site. What's the best way of going about this? | Your answer, Kyle, is the `mu_plugins` folder. Create it within wp-content. Any php file put in here will be automatically loaded into ALL multisite blogs (or any non-multisite blogs).
This is a great area to put plugins vital to the site working, or shared functionality such as custom post types, taxonomies, filters, etc. Really anything! The main bonus here is when updated said "shared" files, you don't have to do it in every single theme that utilizes it! It'll be available for all themes, on all sites.
If you want to sort your stuff within `mu_plugins` just put everything in a nice folder structure, and create a `index.php` or `load.php` in the root of `mu_plugins` where you can load everything in.
From there, `wp_enqueue_script` just as you normally would! | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "multisite, customization, css, javascript"
} |
How can i display the content in plaintext
i want to display my excerpt in plaintext. How can i do this?
This is my Snippet where i display the content:
<?php the_content(__( 'Weiterlesen ›','okay')); ?>
How i change the snippet to display the content in plain?
greets, niklas | Use `wp_strip_all_tags()` to remove the content of `script` and `style` elements too:
echo wp_strip_all_tags( get_the_content() ); | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 12,
"tags": "loop, excerpt, the content"
} |
How to get all post_parents of a post?
Unfortunately, $post->post_parent is a single variable and not an array. I want to get all post_parents of a post (especially of an attachment, which is often linked to multiple posts!). | Based on @Ravs solution I worked this out. This function returns _all_ parent posts, and it checks all attachments attached to all posts.
See this: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, query"
} |
How to fake a Wordpress login?
As many of you know WPEngine don't support PHP SESSIONS unless the user is logged in. In that case WPEngine start taking consideration of PHP SESSIONS and the software based on hybridauth like Wordpress Social Login or Wordpress Social Invitations will work ok.
So my question is : There is a way to fake a Wordpress login? | You could create a dummy user (with no rights) and log in every visitor using this dummy user. This could be done pretty easily:
wp_set_auth_cookie($uid, true);
wp_set_current_user($uid);
But in my opinion that's a rather flawy workaround.
Your main problem is that all pages for not-logged-in users come from the page-cache. That also means that all users get the same html output as long as there is page-caching active. So there can't be any difference to your pages based on the visitor. All visitors get the same output.
A better way would be to create a ticket at WPEngine and ask them to disable page-caching for your site. That's actually also the way they suggest on the page you linked to. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "login, security, wp login form, session, social connect"
} |
Retrieving old forms in Contact Form 7
I recently was having trouble with some of my Contact Form 7 forms so I decided to install the latest version. I backed up (or thought I did) the old version by copying the old Contact Form 7 folder to my computer. Long story short, I had issues with the new version and have chosen to go back to the old. Unfortunately, now that I've copied my backup directory to the WP folder, the plugin works but only one of my old forms is still in the settings menu.
Does anyone know where I can find the rest of the forms I had created? I'm really hoping they're stored somewhere in the directory I copied. Thanks. | Contact Form 7 saves forms and data to the database and not in a directory, except for cahced images like captchas.
Revert the database to recover old forms.
Updating the plugin may irrevocably update the form data, too, so that may be why the forms disappeared. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin contact form 7"
} |
how to make social media buttons start only from under a photo/post?
this is the website <
i want the social buttons from under the post to start everytime under the photo, not on the right of the photo (cause it does that, where it has enough space)
so like in first photo, not like in second.
what kind of condition or what could i use?
i tryed br and p, adding them into the beginning of the share, or the end of the post.. but with no effect. | The element that encases the media share buttons need to have `clear: both` applied to it in your themes style.css .
Add
.fballshare{
clear: both;
}
to the end of your style.css | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
Does WordPress Need BuddyPress to Handle Large Amounts of Users?
I understand that technically there can be 18446744073709551615 users (db limitations). But I heard at a talk that the vanilla install of WP in actuality can't handle many users that well due to caching issues, especially if you add user_meta. Can someone confirm this?
The speaker recommended that to make wordpress more able to handle the large amounts of users it's a good idea to install BuddyPress, but honestly the code is a mess and there is little documentation. So I'm considering scrapping that and going vanilla again.
Does anyone have any expertise and can shed light on this? | I wouldn't advise you to use BuddyPress if you don't have a specific use for any of the special features that are offered by BuddyPress.
From what I've seen from the BuddyPress core is, that it doesn't change any core existing WP functions. So I don't believe that BuddyPress actually changes the handling of user_meta. I seriously doubt that BuddyPress changes anything (wether to the good or to the bad) in regards to the performance of the user handling in Wordpress.
Also from my experience (had up to 15.000 users in one install until now), the performance is still good with vanilla WordPress. No performance degradation measurable. Especially if you have object/database-caching in memory.
If you reach the performance limits of the core API functions you could still easily change your application to hand-crafted and tuned SQL queries and optimize your query and index structure to deliver maximum performance for your specific user_meta queries. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, buddypress, user meta, scale"
} |
index.php file in wp-content/themes/ folder
I was manually uploading a theme im working on to my wordpress install tonight when I noticed a index.php file in my themes folder. I opened the file and it contained only the following three lines of code:
<?php
//silence is golden
?>
This kind of concerned me, at first I thought well maybe I accidentally uploaded the file to the themes directory, but the contents of the file are not anything I would have put.
So what I am getting at is, should there be a index.php file in my wp-content/themes/ directory? Or is it possible someone put it there. OR! Now that I think of it, maybe the file was accidentally uploaded by myself, and then a "hacker" or someone who got access to the directoy changed the contents to include only that one comment, hoping it would break the site.
Not really a code question but I wanted to get some input on this situation. | This file and the copy in `wp-content/plugins/` was added 2009 to prevent directory browsing even when the server allows that.
This isn’t really a security feature, except in the sense of _security by obscurity,_ but there might be files not everyone wants to see published or indexed by search engines.
A better solution is: turn directory listing off (Apache, nginx, IIS) and disallow crawling of these files – even when there are links to single files – in your `robots.txt`:
User-agent: *
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content/plugins
Disallow: /wp-content/themes | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, directory"
} |
Getting "Invalid argument supplied for foreach()" Warning
I am on the last step in a tutorial that I followed here , called "Using the data".
I tried using//
$album_repeatable = unserialize($post_meta_data['album_repeatable'][0]);
echo '[ul class="album_repeatable"]';
foreach ($album_repeatable as $string) {
echo '[li]'.$string.'[/li]';
}
echo '[/ul]';
But I get the Warning as stated in Question Title//
" _Warning: Invalid argument supplied for foreach()_ "
What exactly is the issue here? | Used normal method to get field data instead of " _unserialize_ "
Switched this line:
$album_repeatable = unserialize($post_meta_data['album_repeatable'][0]);
to this line:
$album_repeatable = get_post_meta($post->ID, 'album_repeatable', true);
Now my repeatable field Data is being displayed.
Thanks @toscho for pointing it out... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields, php"
} |
Show post count in wordpress instead of page count in wordpress pagination
Iam using wordpress numbered pagination function, it works good I have around 800 posts on homepage, every page i show 8 posts.
So when the user clicks on pagination i want to show 1-8 of 800. 1st post out of 8 total 800 then user clicks 2nd page - i want to show 9-16 of 800 how to implement i researched a lot. | /**
* Display pagination information in the format "X - Y of Z".
*
* @param object $wp_query Optionally generate string from custom query, defaults to main.
*/
function wpse_106121_posts_count( $wp_query = null ) {
if ( ! $wp_query )
global $wp_query;
$posts = min( ( int ) $wp_query->get( 'posts_per_page' ), $wp_query->found_posts );
$paged = max( ( int ) $wp_query->get( 'paged' ), 1 );
$count = ( $paged - 1 ) * $posts;
printf(
'%d - %d of %d',
$count + 1,
$count + $wp_query->post_count,
$wp_query->found_posts
);
}
Place the above in your `functions.php`, then call it where you'd like to display the text:
<?php wpse_106121_posts_count() ?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "pagination"
} |
Width 100%: Aspect ratio of image
If I add an image to a post, WordPress hardcodes `width` and `height` attributes to the `img` tag.
I added `max-width:100%` to my CSS, but of course, if my browser window gets smaller, the resized image gets stretched in height.
What can I do about it?
Is there a way to:
**A** : Solve it with CSS (I would prefer that)?
**B** : Forbid WP to hardcode width and height?
or
**C** : Is there a common way of dealing with image widths, I'm not aware of? | **A** \+ **C** :
img.resize-proportionally {
max-width: 100%;
height: auto;
}
As an aside, for the above to work, you shouldn't attempt **B**.
Having `width` and `height` attributes in the `img` tag is good. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "images, css"
} |
Get all terms, including unchecked, or get the terms outside loop
I'm trying to return all the terms for a particular taxonomy (so eventually I can create a link for it). At the moment, this function I've written only returns terms for the current post. How can I just return a list of all of them?
<h2>Get terms</h2>
<?php
$taxonomies=get_taxonomies('','object');
foreach($taxonomies as $tax){
echo "<h2>$tax->name</h2>";
$terms = get_terms($tax->name);
foreach($terms as $term){
print_a($term->name);
}
}
?>
Just for a bit more detail, the site is about wine, and one taxonomy is grape type. If the current wine is a Chardonnay, it returns "Chardonnay", but I'd like it to return "Chardonnay, Merlot, Pinot Grigio" etc.
The `print_a` function is just a `print_r` wrapped in pre tags.
Thanks | Ah, my fault I got it, the all important `hide_empty=0`
## Get terms
<?php
$taxonomies=get_taxonomies('','object');
foreach($taxonomies as $tax){
echo "<h2>$tax->name</h2>";
$terms = get_terms( $tax->name, 'orderby=count&hide_empty=0' );
foreach($terms as $term){
print_a($term->name);
}
}
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
How would I get a list of posts from a custom post type
I know the query method that you would use, that's not what I want. I could query the post type, then do the if statement with the while statement and go from there, but I am trying to populate a drop down with post titles. Thus I need an object.
What I have, which isn't working - there should be two posts in this object but their isnt, it comes back NULL, is:
$args = array('post_type' => 'carousel', 'suppress_filters' => 0, 'numberposts' => -1, 'order' => 'ASC');
$content_block = get_post($args);
var_dump($content_block) // NULL
What would I do to get all the posts of the type `carousel`? which I know for a fact has 2 posts in it. I can go to `site.com/carousel/ctitle` to see `ctitle`'s content. But when I try the above I get `NULL` | $args = array(
'post_type' => 'carousel',
'suppress_filters' => 0,
'numberposts' => -1,
'order' => 'ASC'
);
$content_block = get_posts( $args ); // there was a typo in this line
var_dump($content_block); // it should work fine now
PS. I'm not sure why do you need "an object" and you can't do it with custom WP_Query. In the end, `get_posts` function builds custom WP_Query and returns result of it... ;)
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, query, post type"
} |
After I set the title, it over-wrote all the titles for the individual pages
A few days ago I set the title tag for my home page by doing this:
Settings => General
but it turned out that this didn't just change the title of the home page. It actually changed the title of every page on the site to that one title.
What is the way for me to correctly set the title for the home page, and not over-write the titles for all the individual pages?
EDIT:
To explain things further. I set the title tag to be this:
<title>0xdata - Open source software engineering developer community and events</title>
But now the individual pages have titles like this:
Title - Open source software engineering developer community and events » Open source software engineering developer community and events
Thank you! | WordPress sets the titles of your pages using tags which is normally set int he header.php file of your theme. In my themes I use:
<title><?php bloginfo('name'); ?> <?php wp_title(); ?></title>
Find your themes header.php and try changing the code inside the tags to the code above. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "title, wp title"
} |
Wordpress custom search by post type
Is it possible:
If post type is post, search only in post title. If post type is page, search only in post content.
I was trying in any ways but didnt worked, maybe someone could help me ? | Yes, it is possible. You will have to use your custom SQL query though.
Use `posts_where` filter to modify the query.
function posts_where( $where ) {
if( !is_admin() ) {
$where = <YOUR CONDITION>;
}
return $where;
}
add_filter( 'posts_where' , 'posts_where' );
Your condition should look something like this:
`post_status = 'publish' AND ((post_type = 'post' AND post_title LIKE <QUERY>) OR (post_type = 'page' AND post_content LIKE <QUERY>))`
You should also make sure, that you will modify only main query and not all of them. You can add filter just before main query (i.e. using `pre_get_posts` action) and remove it just after or even inside this filter, I guess. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "search"
} |
How to target specific user role?
I'm trying to place a simple bunch of codes to redirect the 'Subscribers' only, to the home page (or a desired page) after login. I thought to use `if( current_user_can('read') ):`, but that's a global capability, will be applicable for all the other roles too. So I tried `get_role('subscriber')`. Here are my `functions.php` codes (thanks to Len):
function subscriber_redirection() {
global $redirect_to;
if( get_role('subscriber') ) {
if ( !isset( $_GET['redirect_to'] ) ) {
$redirect_to = get_option('siteurl');
}
}
}
But it's redirecting the administrators too!
* **How can I target only a specific user role for a purpose?** | `get_role` is just going to return information about the role. It isn't going to tell you if the current user has that role. Use `wp_get_current_user` with a check something like this:
function subscriber_redirection() {
global $redirect_to;
$user = wp_get_current_user();
if (in_array('subscriber',$user->roles)) {
// user has subscriber role
if ( !isset( $_GET['redirect_to'] ) ) {
$redirect_to = get_option('siteurl');
}
}
}
I don't know why you are using `global $redirect_to;` but never do anything with the variable. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "redirect, user roles"
} |
How Wordpress remembers which active editing modes are used?
I noticed that when I save page in Visual editor. Wordpress remembers it the next time I edit the page even if I clear all my browser cookies and cache.
In what section of the WordPress database does this setting is saved? I searched for it and couldn't found it. | WordPress stores this option as user meta ({$wpdb->prefix}user-settings).
You can use `get_user_setting('editor', 'tinymce')` to get it's value (`editor` is setting name, and `tinymce` is default value). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp editor"
} |
Show one same template for two category
I want to show `gallery.php` template for category. I am currently using `category-15.php` and `category-19.php` technique.
I want to redirect category 15 and 19 to `gallery.php` instead (one template for two category). And I want to use a simpler technique. It can be by using `functions.php`.
How can i do it? | You can do it in many ways.
Two solutions I recommend are:
## 1\. Editing category template
Just edit your `category.php` template and put if statement in there:
if ( is_category( array(15, 19) ) )
get_template_part('category-15-19');
else
get_template_part('category-all')
Then just put code for category 15 and 19 into `category-15-19.php` file and code for other categories into `category-all.php` file.
## 2\. Using `template_include` hook
Add filter to `template_include` hook. It should return template name that should be displayed by WordPress.
function my_categories_template($template_name) {
if ( is_category( array(15, 19) ) )
return 'category-15-19.php';
return $template_name;
}
add_filter( 'template_include', 'my_categories_template' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
Do more action after login successfully
I have a simple requirement, after user login set the login user session and then redirect to another page.
Yes, I found some similar page from here is-there-a-hook-that-runs-after-a-user-logs-in
As the post said, what I need to do is like this:
function set_blog_session(){
$_SESSION['blogger'] = get_current_user_id();
wp_redirect(" for test
}
add_action('wp_login', 'set_blog_session');
But I got nothing.
First, `get_current-user_id()` always returns `0`.
Second, **no redirect at all**.
Whats going wrong? | You should use `exit` after using the `wp_redirect()`:
From the Codex:
> wp_redirect() does not exit automatically and should almost always be followed by exit.
* * *
For your hook, you could pass a parameter in your callback function to get the user login and then use `get_user_by()` to get the ID.
function set_blog_session($user_login){
$user_obj = get_user_by('login', $user_login );
$_SESSION['blogger'] = $user_obj->ID;
wp_redirect("
exit;
}
add_action('wp_login', 'set_blog_session'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "login, wp redirect"
} |
How to translate content in category.php or index.php with qtranslate?
I was wondering how to translate content under `index.php` (or `category.php` with qtranslate?).
I'm using twenty twelve theme.
My code on `index.php`:
<?php
/**
* The main template file.
* @package WordPress
* @subpackage Twenty_Twelve
* @since Twenty Twelve 1.0
*/
?>
<?php get_header(); ?>
<?php
$page_id = 1500;
$page_data = get_page( $page_id );
echo apply_filters('the_content', $page_data->post_content);
?>
<section id="last-articles_homepage">
<h1>Latest News</h1>
...
I would like to translate the content inside the `<section>` and `<h1>` tag for example in french. | Most correct way to do this would be to use WordPress translations.
You should replace this static text with:
<?php _e('YOUR TEXT', 'your_text_domain'); ?>
And add text domain to your theme.
More on this topic: <
## You can also...
... use `qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage` function.
Just use it like so:
<?php echo qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage('<!--en:-->Latest News<!--:--><!--fr:-->dernières Nouvelles<!--:-->'); ?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "plugin qtranslate"
} |
Put a link to a category round a hard coded A HREF
In my footer I have hard coded the links and would like to link some to there category, I could just copy the full URL to it and paste in the href="" but I would rather call it using php.
My knowledge of WordPress and PHP is little and I have tried searching for something that will do this but none work, my last go used this:
<a href="<?php echo get_permalink( get_page_by_path( 'cooking-sauces' ) ); ?>">Cooking Sauces</a>
and I tried this:
<a href="<?php echo get_permalink( get_page_by_path( 'cooking-sauces')->ID); ?>">Cooking Sauces</a>
but did not work.
So the full URL would be <
Please can some one help, many thanks Dave
UPDATE: Could it be called using the SLUG and if yes have is this done please. | The "page" in WordPress usually refers to a "PAGE page", as in only post of `page` post type. Not any _page_ of the site in general.
What you want to link to is _category archive_. Something along this should work:
echo get_category_link( 'cooking-sauces' );
If `cooking-sauces` is slug of a _term_ that belongs to custom _taxonomy_ (as opposed to native _category_ taxonomy) you will probably need to use something like:
echo get_term_link( 'cooking-sauces', 'your-taxonomy-slug' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, categories, permalinks, slug"
} |
failed to load wp-admin/admin-ajax.php
I'm getting this strange issue. Everything was working fine last day. Now suddenly none of my ajax requests work. The problem is (i found that in firebug console):
> failed to load resource : ....../wp-admin/admin-ajax.php
So somehow the request to the `admin-ajax.php` file isn't successful. I have cross checked these things:
1. the url to `admin-ajax.php` is correct and no issues there
2. its not just 'my own scripts' which doesn't work, i've buddypress installed and all ajax requests from buddypress also give the same error
3. i directly typed in the url of `admin-ajax.php` into browser and instead of getting 0 (the expected output), google chrome says 'no data received'.
Is it some configuration on server end?? If yes then what do i say to the hosting support guys?
BTW, if it matters, the site is hosted on wpengine..
Any help is really appreciated
**UPDATE :** the browser dev tools screenshot : !enter image description here | Yes finally the problem was that the hosting provider had blocked the admin-ajax.php file saying that this file was receiving too many request, and requests to this file bypasses cache , hence it was causing problems on server :)
So now i'll have to 'convince' them to turn it back on.
Thank you all for helping.. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 8,
"tags": "ajax"
} |
enqueue script if page is not equal to
I'm registering some js scripts in my function.php, I have 2 versions of one js file, one FOR the homepage, and one for every other page.
I've managed to get this to work to register the homepage script successfully:
function home_script_method() {
wp_register_script( 'homescript', '/wp-content/themes/template/js/menu-home-open.js' );
if( !is_page( 'home' ) ) // If it's not the given page, stop here
return;
wp_enqueue_script( 'homescript' );
}
add_action( 'wp_enqueue_scripts', 'home_script_method' );
But is it at all possible to register an alternative script for every other page, i.e. if on the homepage then register `menu-home-open.js`, if on any other page then register `menu-open.js`. Is that at all possible? Can't seem to get it to work, any suggestions would be greatly appreciated! | add_action( 'wp_enqueue_scripts', 'ron_scripts' );
function ron_scripts(){
if(is_home()){
wp_register_script( 'homescript', '/wp-content/themes/template/js/menu-home-open.js' );
wp_enqueue_script( 'homescript' );
} else {
wp_register_script( 'nothomescript', '/wp-content/themes/template/js/FILENAMEHERE.js' );
wp_enqueue_script( 'nothomescript' );
}
}
alternatively replace `is_home();` with any other method or code that determines what page you are on. ex:
might work
if(site_url() == get_permalink()){
//do home stuff
} else {
//do not home stuff
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, functions, jquery, wp enqueue script"
} |
Load code for custom fields only on admin pages?
Is this possible?
I have big chunk of code for creating and saving custom meta fields, and I have a feeling that this has some impact on wordpress loading time ( **?** ).
I tried with
add_action('init', 'admin_only');
function admin_only() {
if ( is_admin() ){
require_once('functions_admin.php');
}
}
but on **"add new post"** screen custom fields are missing. | Loading this code won't have big impact on loading times.
Of course you should make sure, that this code is only executed when it should be...
But yes, it should be possible. Just make sure you don't use it to early (when `is_admin()` return incorrect value).
**EDIT**
The code you've posted here should work just fine. Of course you have to make sure that code placed in `functions_admin.php` is written correctly (for example you have to take care of using global variables in correct way).
To test if this is included, just add `echo 'alamakota';` in first line of this included file and check if 'alamakota' is showing on every admin page (it should).
Also make sure that you don't add filters/actions to hooks that are run before `init` hook. The won't fire up (WordPress already called these hooks before you added your filters). See: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field"
} |
CSS Classes (optional) on menu is not showing
As you know, there are input boxes for CSS Classes (optional) on each menus.
But it's not showing (coming out) in source. Is there any function for disable for CSS Classes (optional)? I need to find it and remove it.
my another sites work fine like this. I put "navi_box1" on Menu1 as CSS Class. and it shows right spot.. `<ul id="menu-menu-box" class="menu"><li id="menu-item-422" class="navi_box1 menu-item menu-item-type-custom menu-item-object-custom menu-item-422"><a href="/" class="has-submenu">Menu1</a> ..........etc....... </ul> `
this is the codes for navi..
wp_nav_menu( array( 'container' => false, 'menu_class' => 'left', 'theme_location' => 'primary', 'fallback_cb' => 'sweetdate_main_nav', 'walker' => new sweetdate_walker_nav_menu) );
the name of theme_location is right. | The obvious answer is that `sweetdate_walker_nav_menu`, which is the walker that creates this menu, is written is such a way as to not print those classes. It is hard to say for sure without seeing the code for that custom walker but you can remove the `'walker' => new sweetdate_walker_nav_menu` argument to verify that that is the problem. If it is you'd have to write code into the walker so that it uses those classes.
There is also a filter called `nav_menu_css_class` which I believe is what one would use to remove those classes. However, there are numerous other filters in `nav-menu-template.php` and `nav-menu.php` that could potentially be involved. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, css"
} |
WYSIWYG with HTML source?
I'm trying to switch from Drupal to WordPress, and I have lots of articles written in Drupal's WYSIWYG Editors, and stored like
<p>Hi, this is an article</p><p><img bla='bla'></img></p>
So I want to directly copy the source code and paste it into WordPress. I can do it by disabling the visual text editor. So it works for migrating existing articles in.
But what about writing new articles?
I couldn't find any wysiwyg editors that automatically insert `<p>` tags. I tried the Ultimate TinyMCE plugin, but it only adds some buttons, does not change the situation.
**To summarize my problem:**
When I write
Article line 1
Article line 2
in the "Visual" Tab, I want to see
<p>Article line 1</p><p>Article line 2</p>
in the "Text" Tab.
But instead, I see exactly what I wrote, and this causes bad HTML output, when getting `$post->post_content;`
Thanks ! | It seems the solution for this is the plugin called TinyMCE Advanced.
Just install it, and go to Settings -> TinyMCE Advanced -> Check the box where it says `Stop removing the <p> and <br /> tags when saving and show them in the HTML editor` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tinymce, html, wysiwyg, html editor"
} |
Featured Images for Tags?
Is it possible to somehow create featured images for tags or custom taxonomies.
For the sake of explanation, I will give an example of the possible functionality.
Say I am running a website that posts the best restaurants by city. Some of my tags could be London, Paris NYC, etc... I have a page that grabs these tags and sorts them alphabetically. But rather than just have text, it would have the tag name (London for example) and an image for that city.
I know this could be done manually, but by attaching an image to the tag or custom taxonomy, it could make the process a bit easier, especially if dealing with a great number of tags/custom taxonomies.
I reckon this might be a bit more of an abstract question, but I am curious if anyone has come across any blogs or websites that are doing this successfully. | I use this plugin for exactly the same purpose (and for other taxonomies we got that need a featured image): < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, customization, images, tags"
} |
Unescape attribute the_title() on CDATA in RSS feed
My goal is to **unescape the string**.
So, how would I do it in Wordpress? Let's say I have the whole string below:
He said, “This is how it works...”
I can't seem to find a built-in Wordpress function to unescape `“` and `”`. This is if using unescape on `the_title()` (sorry for not specifying earlier).
On the rss feed items, I have this code where `the_title()` should be unescaped:
<item>
<title><![CDATA[<?php the_title(); ?>]]></title>
<link><?php echo get_permalink(); ?></link>
<date><?php the_time(get_option('date_format')); ?></date>
</item> | I don't think there is one. Escaping is harder than unescaping (you have decide what exactly to escape and where).
Just use PHP `html_entity_decode` function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions"
} |
Display filesize of custom field value
I wanted to display the filesize of a document (pdf, word, excel etc) from a custom field. I already search and I found nothing. I got this code from other site but its in PHP. So I add it manually to my theme.
if($kpmFile !== get_post_custom_values("kpm_UploadFile")) {
$head = array_change_key_case(get_headers($kpmFile, TRUE));
echo $filesize = $head['content-length'];
}
I get this warning from above code:
Warning: get_headers() [function.get-headers]:
But if I make it like this:
if($kpmFile !== get_post_custom_values("kpm_UploadFile")) {
$head = array_change_key_case(get_headers(" TRUE));
echo $filesize = $head['content-length'];
}
The code will show the filesize in 44147474 which the file is actually 42.1MB
I need help on how to display the correct file size of the document in kb, mb or gb from custom field value.
Thanks in advance. | function to handle to show file size i.e.
paste this code in functions.php
/*
* @param string $fileSize Filepath
* @param int $digits Digits to display
* @return string|bool Size (KB, MB, GB, TB) or boolean
*/
function getFilesize($fileSize, $digits=2) {
$sizes = array("TB","GB","MB","KB","B");
$total = count($sizes);
while ($total-- && $fileSize > 1024) {
$fileSize /= 1024;
}
return round($fileSize, $digits)." ".$sizes[$total];
}
paste this code in single.php
if($kpmFile !== get_post_custom_values("kpm_UploadFile")) {
$head = array_change_key_case(get_headers(" TRUE));
echo $filesize = getFilesize($head['content-length']);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "custom field"
} |
conditional statement for custom taxonomy
Struggling to find out how to achieve this, if it is at all possible. The equivalent of `is_category` but for a custom taxonomy I've set up. The taxonomy category if which being `Taxonomy Name` with 2 taxonomies: `Taxonomy One` and `Taxonomy Two`. But this:
<?php if ( has_term('taxonomy-one' ) ) {?>
<div class="test" style="color: red"><?php the_field('field_name'); ?></div>
<?php } elseif ( has_term('taxonomy-two' ) ) {?>
<div class="test" style="color: green"><?php the_field('field_name'); ?></div>
<?php } ?>
There doesn't seem to be any documentation for this either so I'm not at all sure if it's possible, I'm hoping so though, any suggestions would be greatly appreciated! | I'm pretty sure you shouldn't use negation in your conditions... If you check `! is_tax...` it will be true not only for other taxonomy pages, but also for singular pages, and any other...
So it should look like this:
<?php if ( is_tax('taxonomy-name','taxonomy-one' ) ) {?>
<div class="test" style="color: red"><?php the_field('field_name'); ?></div>
<?php } elseif ( is_tax('taxonomy-name','taxonomy-two' ) ) {?>
<div class="test" style="color: green"><?php the_field('field_name'); ?></div>
<?php } ?>
And about lack of documentation... I have no idea where have you looked for, but there is codex page for `is_tax`: < ;)
PS. If you want to check if given post is assigned to term, then you should use `has_term` function. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "php, custom taxonomy, taxonomy, conditional tags, conditional content"
} |
Editing 'Password Reset' E-mail
I'm trying to customize the e-mail that you receive from WordPress when you reset your password. Right now it's a WordPress e-mail but I'd like to brand it with our company's logo and custom information (but of course keep the reset password link).
I've been digging around the wp-login.php page but haven't tracked down where that is controlled. I'm well-versed in the PHP mail function (which I'm assuming is called here) so I can edit it if I find the code. Does anyone know where that code is? Thanks! | WordPress uses custom `wp_mail` function, so you won't find it, if you'll search for `mail`.
Just take a look at line 248 of `wp-login.php` file: <
You should find `retrieve_password_message` filter call there. This is the filter that returns the content of reset password message.
You should also check the implementation of `wp_mail` function, because you will have to add headers to your mail (you want to send it as html and not as plain text, I guess). You can use `wp_mail_content_type` filter to change it. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "filters, login, email, password"
} |
How to display price including tax with formatting?
The code below will show the price including TAX and it works for single page, but on category pages it's missing the Thousand Separator and Currency Symbol.
It is showing as `21000.23` and not `21,000.23`.
Here's the code used in the category page.
<?php if ( $price_html = $product->get_price_including_tax() ): ?>
<span class="price"><?php echo $price_html; ?></span> | Running any number through the function `woocommerce_price()` will format that number with the number of decimals, thousands separator, currency symbol and currency location chosen in the admin.
Add the function to your code snippet should format the price correctly:
<?php if ( $price_html = $product->get_price_including_tax() ): ?>
<span class="price"><?php echo woocommerce_price($price_html); ?></span> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins"
} |
showing 2 prices wholesale and normal
am using the plugin Ignitewoo Wholesale price and have coded the single-product page to show two prices with the idea of one being the wholesale price the other normal retail price but atm its showing both wholesale price how can i change one to be only normal price?
<p itemprop="price" class="price"><?php echo woocommerce_price($product->get_price_including_tax()); ?>
<span class="pcat"><?php
if ( is_user_logged_in() ) {
?>
trade
<?php } else { ?> rrp <?php } ?>
</span></p>
<?php
if ( is_user_logged_in() ) {
?>
<p itemprop="price" class="rrpprice"><?php echo woocommerce_price($product->get_price_including_tax()); ?> <span class="pcat">rrp</span> </p>
<?php } else { ?> <?php } ?> | Read directly from the database so that no PHP interferes with it. using the postmeta field _price..
<?php echo woocommerce_price( get_post_meta( $product->id, '_price', true ) ) ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, plugins"
} |
May I change the order of the tags?
I have a list of all tag. I want set a order for them, form example, as order of slug? Here is the code for get all tags.
<?php
$tags = get_tags();
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id);
$html .= "<a href='{$tag_link}' title='{$tag->name}' class='{$tag->slug}'>";
$html .= "{$tag->name}</a>";
}
echo $html;
?> | You'll have to specify the `order` and the `orderby` parameters within `get_tags()`. If you want an ascending order by slug you can update youre code snippet this way:
$tags = get_tags( 'order=ASC&orderby=slug' );
There are also a lot of other parameter as you can see in the codex: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "tags"
} |
Multisite Network Localisation
The problem seems easy to solve - I have installed multisite network, each new page have Polish language set as default, polish localisation files are in right directory, in wp_config there is line: define('WPLANG', 'pl_PL'); Sites admin panels are correctly in polish language, but global network admin isnt. What am I missing to turn network admin panel to polish language? | Re-saving the language of the first site with the **ID #1** solved the problem.
One can do this within _Settings » General » Site Language_ | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, localization"
} |
Same post appears in related Posts?
Here is the code
function dark_delight_get_related_posts(){
$post = get_post();
$args = array(
'posts_per_page' => 4,
'ignore_sticky_posts' => true,
'posts__not_in' => array($post->ID),
);
$categories = get_the_category();
if( !empty($categories) ){
$category = array_shift( $categories );
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category->term_id,
),
);
}
return new WP_Query( $args );
}
I opened 'Hello world!' post and it shows up in the Related posts too. | Aahhh, it's a typo, I guess.
There is no parameter called `posts__not_in`. It's called `post__not_in`.
So you should change your code to:
function dark_delight_get_related_posts(){
$post = get_post();
$args = array(
'posts_per_page' => 4,
'ignore_sticky_posts' => true,
'post__not_in' => array($post->ID), // post and not posts
);
$categories = get_the_category();
if( !empty($categories) ){
$category = array_shift( $categories );
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category->term_id,
),
);
}
return new WP_Query( $args );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, functions, wp query"
} |
Dynamic sidebar based on category
I am new to wordpress, i have developed a basic theme to make a tutorial web site, for that i need a dynamic sidebar based on category,
suppose, i have category A & B, if user is on the A category i need to display A sidebar, if it's in B category need to display B sidebar,
The sidebar will hold the menu items.
for Demo website see: < click on the any manu and see the sidebar.
i have searched plugin to achieve the stuff, but can't find it. if there is any plugin please suggest, | There are many solutions to your problem, I guess. Two solutions I would recommend are:
## 1\. Register multiple sidebars.
Register more sidebars and then include them conditionally in page templates. So if you need different sidebar for each category (let's say you have 2 categories), then register 2 more sidebars (sidebar-cat-1, sidebar-cat-2) and then replace generic sidebar with one of these two, based on what category is displayed.
## 2\. There is plugin for that ;)
You could check these plugins:
* <
* < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "widgets, sidebar"
} |
Location of core code for database connection and get_header
I understand WP well enough to create a custom theme at a basic level, but have no experience with the core code. I've also just finished a book on basic php and mysql coding.
I'd like to look 'under the hood' of WP to try and put those together. Can someone tell me:
* Where to find the files that code for the WP-Mysql connection? (as in, `mysqli_connect` ...)
* Where to find the files that code for the `get_header()` function? (which I assume will have something like `include(header.php)` )
Thanks! | First off, the usual caveat -- _Don't modify core code_. (Certainly not on a production site.)
If you read the documentation on the Codex, you'll notice that most if not all of the pages in, say, the Function Reference have a section called **Source File**. Clicking the link located there will take you to the file in trac where the particular function lives.
For instance, the Codex page for `the_ID()` points you to `wp-includes/post-template.php`.
Your specific questions:
* The `$wpdb()` class is in `wp-includes/wp-db.php`.
* `get_header()` is in `wp-includes/general-template.php`.
Sometimes, though, you'll have to hunt all over the WordPress codebase to follow the track of _how does this work?_ You'll find that functions call other functions, which call other functions, which apply filters, and so forth. There's a lot of digging, sometimes, to understand how something in WordPress actually works. Do it. It's worth it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, mysql, headers, core"
} |
Advanced Custom Fields plugin : displaying a field while omitting the p tags
In Advanced Custom Fields plugin, is it possible to display a WYSIWYG editor field in which `p` tags are omitted? | `strip_tags()` is not bad, but there may be a lot of tags you'll have to allow. So maybe you can use `str_replace()` to only get rid of the `<p>`-tag:
<?php
$field = get_field('wysiwyg'); // your wysiwyg field data
$strip = array('<p>','</p>'); // search for <p>
echo str_replace($strip,'',$field);
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields, wysiwyg"
} |
Adding custom HTML to each profile group tab
Hopefully someone can help. I am looking to add a different image banner to each of the profile group tabs I have on my Buddypress site. I have identifed the profile-loop.php as the file I need to include this on but when I try the following code it breaks the profile section of my site:
<?php if ( bp_the_profile_group_name() == 'About') ) : ?>
<h4>Testing</h4>
<?php endif; ?>
Can anyone suggest how I might target the About group on my site and insert custom HTML?
Thanks | Think I have figured out how best to work this. For anyone that may need it sometime the code I used was:
<?php if ( 1 == bp_get_the_profile_group_id()) : ?>
<h4>About Me</h4>
<?php endif; ?>
With 1 == the profile tab where I need to add my custom HTML. If anyone has a better solution I am open to them. Thanks. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "buddypress, profiles"
} |
Close a wordpress blog - keep site as it is but prevent hacks
Last summer I created a travelling-blog on my webspace to document my journey. Now the journey is over and I won't put any new posts in this blog. I also don't whish to have any new comments.
How can I close the blog (to make in invulnerable to external hacks, even if I don't install any new upgrades) but keep all posts, comments, pictures, etc. as they are?
What I found is
* < (however, although the resulting static page contains all the blogged content, the design is really messed up.)
* < (I couldn't try this one, because it is written in python and I don't know any python.)
~~Is one of them recommendable?~~
Is there another way to prevent all interactions with the page, so there's no need to take care about wordpress (or plugin) updates, while still keeping the site secure? | Why not just disable comments and registration?
This comes to mind also:
(Redirect all requests to login page or admin pages to homepage. A little irreversible.)
$currentURL = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
if (strpos($currentURL, 'wp-admin' ) or strpos($currentURL, 'wp-login' )) {
header( 'Location: '.site_url() );
}
Caution: this stops you from logging in also.
Edit:
And adaptation of the above code put into plugin format can be found here. Thanks to brasofilo.
Modified code:
add_action( 'init', function()
{
$currentURL = $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
if( strpos( $currentURL, 'wp-admin' ) or strpos( $currentURL, 'wp-login' ) )
exit( wp_redirect( site_url() ) );
} ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "security, static website"
} |
Failed to open stream: HTTP request failed! in \wamp\www\wordpress\wp-includes\class-http.php on line 929
I'm writing a theme and almost every time I reload a page, WordPress is giving the following error
> Warning: fopen(< failed to open stream: HTTP request failed! in D:\wamp\www\wordpress\wp-includes\class-http.php on line 92
As can be seen I have enabled `WP_DEBUG`. Here is a screenshot of the warning window (click to zoom):
 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp cron, http, wp debug"
} |
Update plugin settings option_name for big plugin update
I am working on a plugin update and have changed the settings option_name and key.
I would like that the old options are transferred to the new option_name.
The old option name is: plugin_options
The new being: plugin_settings_general
The keys have changed too, from "ga_accountId" to "ga_account_id".
I looked at $wpdb and update_option but could not working any thing out that worked.
This should work if I did not need to change the keys too.
// Get entire array
$plugin_options = get_option( 'plugin_options' );
// Update entire array
update_option( 'plugin_name_settings_general', $plugin_options );
// Delete old array
delete_option( 'plugin_options' ); | I think changing array keys is more of a PHP problem
// Get entire array
$plugin_options = get_option( 'plugin_options' );
$new_options = array();
if( isset( $plugin_options['ga_accountId'] ) )
$new_options['ga_account_id'] = $plugin_options['ga_accountId'];
// Update entire array
update_option( 'plugin_settings_general', $new_options );
// Delte old array
delete_option( 'plugin_options' );
Any end-user who might be using using your plugin's options for something in their theme, will get errors. But if you are going to rename things, `plugin_settings_general` should be name-spaced with your plugin's actual name. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, database, settings api"
} |
Wordpress: Apply filter/hook to a particular sidebar widgets?
I'm developing a theme that has more than 5 different sidebars and I want to apply a function to a particular one of them for styling purposes. Basically, the function will modify it's params using a counter to show random 's between each of the widgets. I came up with that:
function widget_params( $params ) {
// ...
}
add_filter( 'dynamic_sidebar_params', 'widget_params' );
But however, it will run for each and every different sidebar. Is there any way to make it work only on a particular sidebar? Or alternatively, is there any way to get current widget's sidebar id inside of that function?
Hope all of that makes sense.
Thanks in advance! | If you were to add `var_dump($params);` to the top of your callback you'd notice that it contains references to both the sidebar name and the sidebar ID. You can use those to control when this runs, provided you know the name or ID.
function widget_params( $params ) {
if ('Main Sidebar' === $params[0]['name']) {
// do something
}
return $params;
}
add_filter( 'dynamic_sidebar_params', 'widget_params' ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "widgets, filters, hooks, sidebar"
} |
wp_dropdown_categories - remove
I need to remove the auto adding of ` ` in the `wp_dropdown_categories`, it causes a problem in the jQuery multi select dropdown plugin I'm using.
Example value:
<option class="level-1" value="120"> Apples (125)</option> | You could use the `echo` parameter to return the output into a variable:
$html = wp_dropdown_categories( array( 'echo' => 0 ) );
and then replace ` `:
echo str_replace( ' ', '', $html ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "dropdown, categories"
} |
Remove posts from two categories in Archive Page
From Archive Page I want to remove posts from couple of categories, as they have different style formats which will not look good with other category style formats. | try this...
**Not Tested**
add_action("pre_get_posts","my_category_remove");
function my_category_remove($query)
{
if(is_archive()) {
$query->set('category__not_in', array(/*the categories (ID's) you wish not to show, comma separated*/));
}
return $query;
}
Reference | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "archives"
} |
Custom Post type plugin breaking the front page shows dashboard?
I am following the wp.tutsplus tutorial on Custom post types. Everything was fine until i added this code in my main plugin file
<?php add_filter( 'template_include', 'include_template_function', 1);?>
<?php function include_template_function(){
if( get_post_type() == 'movie_reviews' ){
if( is_single() ){
if( $theme_file = locate_template( 'single-movie-reviews.php' ) ){
$template_path = $theme_file;
}
else
$template_path = plugin_dir_path( __FILE__ ).'single-movie-reviews.php';
}
}
return $template_path;
}
?>
I can still access the dashboard and create new posts but front page is blank. if i remove this code page loads without any problem. | > To solve your issue with the page template not showing up in the template dropdown list
In your `single-movie-reviews.php`, add the following at the top of the file:
<?php
/*
Template Name: My Custom Page
*/
Where you change `My Custom Page` into the template name of your choice.
See **This Codex page** for more information about Custom Page Templates. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, custom post types, errors"
} |
Bootstrap Error in WordPress plugin
I am creating a plugin that generates advanced search queries. All of the UI is done in bootstrap, and the results are displayed via modal (bootstrap.js). On the production site Greenlane SEO I get the JS error: `Uncaught TypeError: Object [object Object] has no method 'modal'`. I cannot figure out for the life of me what is causing this as I installed this on another WP site and the plugin works seamlessly (minus the styling). | You are loading jQuery 1.8.3 and jQuery 1.9.1. 1.8.3 loads from `wp-includes`. 1.9.1 loads from Google. Install JSView on FireFox and right click the page. You will see them. There are two Javascript files, both named `jquery.js`.
You need to work out what is loading those two scripts and make sure that only one jQuery gets loaded, and it will have to be the right one. Hopefully that is the most recent one-- 1.9.1 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, twitter bootstrap"
} |
Add information to HTTP Header in WordPress Plugin
I am working on developing a plugin for a tool called Supportify. It is a REST API that is authenticated through a key and token added to the HTTP header of a HTTP request to their servers. Their API reference is here. I know you can add things to the header with `wp-config.php` but for a publicly released plugin this is not feasible. Is there any way to do this through a plugin? | PHP allows you to send header information using the `header()` command.
More specific to WordPress is the `send_headers` action hook.
Also: always remember that you have to send all your headers _before_ any output is sent to the screen. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, http api"
} |
How to grab a specific page of content from paginated post?
In my case I've got to create articles where each article has a custom, unchanging "header" part far too rich for the title and the excerpt (it's to contain image, media etc), and then a few different pages of content. I've decided to do this using `<!--nextpage-->` to keep it lightweight and easy for whoever will create the pages - treat the first page as the unchanging header and attach page 2, 3, 4 under a fixed set of links - an custom menu generated in that category, replacing standard pagination "Page 1 2 3 4" links.
In order to do that, I'll have to call `the_content()` twice; once for page 1, and once for whichever page is chosen through the dedicated menu. Except I have no clue how to make `the_content()` extract _n_ -th page, other than through appending / _n_ / to the URL.
Is there some variable, function, plugin, modification to the code that lets me extract a specific page of paginated post? | `nextpage` pagination is a bit odd. You will have to parse the post content. This should do it.
function get_nth_page($n=0,$content='') {
if (empty($content)) {
global $post;
$content = $post->post_content;
}
if (empty($content)) {
return false;
}
$content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
$content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
$content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
$pages = explode('<!--nextpage-->', $content);
if (isset($pages[$n])) {
return $pages[$n];
}
}
You can pass `$content` explicitly or it will try to grab the `global` `$post` variable. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pagination"
} |
Get post type from taxonomy or category page
This might be somewhat backward, but how can one get the post type being displayed on an archive page? Alternatively, how can one get the post type associated with a given taxonomy? | get_queried_object() is your friend. It will tell you all kinds of information about what your template files are trying to do. From within, you can discover your post type. Try doing a `var_dump` to take a look at that object.
As for your second question, taxonomy is not, as far as I know, isolated to one post_type, so that is not really something one can assume. For example, "location" may be a taxonomy to both post types: "Restaurants" and "Grocery Stores". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, custom taxonomy, archives"
} |
WP Rewrite for a custom variable
I know there are dozens of posts on this, but (I'm embarassed to say this) I'm having a rough time following them.
My goal here is to have `/resources?audience=teachers` become `/resources/audience/teachers` or event `/resources/teachers`.
I have 2 custom taxonomies on attachments - Types and Audiences. I then have a page titled Resources which is going to house all of the attachments within these categories. If an audience of type is specified, I will only display that term's attachments.
I've tried using the following this within an `init` hook:
add_rewrite_rule(
'resources/([^/]+)/?$',
'index.php?pagename=resources&audience=$matches[1]',
'top' );
With no success. I'm sure it's a no-brainer. | You have to use this:
add_rewrite_rule(
'resources/audience/([^/]+)/?$',
'index.php?pagename=resources&audience=$matches[1]',
'top' );
in your `init` hook.
Then you should add your own query variable:
function add_my_var($public_query_vars) {
$public_query_vars[] = 'audience';
return $public_query_vars;
}
add_filter('query_vars', 'add_my_var');
Then flush rewrite rules (go to permalink settings and push "save" button).
After visiting url: `site.com/resources/audience/teachers/` your recources page should be shown. You can get value of `audience` variable with `get_query_var()` function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting"
} |
How to show an image popup when one clicks on an image thumbnail?
I have created a Gallery View shortcode plugin. I wanna add an feature to that which is - Whenever someone clicks on any image in that gallery, that image should get open in a stylish popup window. Since I am seeking to add this feature to my own plugin, I can't even think to use another plugin. I tried to understand the coding of some such plugins but couldn't figure out any proper way to do so. Please suggest! Thanks! | 1) enque thickbox on front end
add_action('init', 'myplugin_thickbox');
function myplugin_thickbox() {
if (! is_admin()) {
wp_enqueue_script('thickbox', null, array('jquery'));
wp_enqueue_style('thickbox.css', '/'.WPINC.'/js/thickbox/thickbox.css', null, '1.0');
}
}
2) Add thickbox to all your images that are displayed by the_content();
function fb_add_thickbox($content){
$content = preg_replace('/<a(.*?)href="(.*?).(jpg|jpeg|png|gif|bmp|ico)"(.*?)><img/U', '<a$1href="$2.$3" $4 class="thickbox"><img', $content);
return $content;
}
add_filter('the_content', 'fb_add_thickbox', 2);
sources: < < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, gallery"
} |
Show uploaded images in full size
I have a very simple template where I am showing images. The code looks like this:
<?php
/*
* Template Name: Portfolio
*/
?>
<?php get_header(); ?>
<div class="row">
<div class="small-12 columns">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php
the_content();
?>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
</div> <!-- #small-12 -->
</div> <!-- #row -->
<?php get_footer(); ?>
The problem is that when I upload my images in the editor, they become much smaller than they actually are (on the page). I control their size by setting `max-width: 100%` in my css already, so I don't want WordPress to limit the size. How can I remove this? | WordPress creates 3 different sizes as far as my research goes. Read this on WP image handling -> <
> You can easily customise the default Media sizes by changing the default sizes in Dashboard > Settings > Media.
You can grab any of those sizes. See the codex @ <
The function you want is:
get_the_post_thumbnail( $post_id, $size, $attr )
And here's an example:
get_the_post_thumbnail($post_id); // without parameter -> Thumbnail
get_the_post_thumbnail($post_id, 'thumbnail'); // Thumbnail
get_the_post_thumbnail($post_id, 'medium'); // Medium resolution
get_the_post_thumbnail($post_id, 'large'); // Large resolution
get_the_post_thumbnail($post_id, 'full'); // Original resolution
get_the_post_thumbnail($post_id, array(100,100) ); // Other resolutions | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, templates, the content"
} |
Redirect outside WP after login
I have `
There I check whether the user is admin or not. If not, I send the user to the wp-login page like this:
blog.mysite.com/wp-login.php?redirect_to=http%3A%2F%2Fmysite.com/admin.php
I expect redirect back for admin.php but WordPress always sends me to `wp-admin` control panel.
After researching, I found that when the destination host is not in filter `allowed_redirect_hosts`, WP just redirects the user to `wp-admin`.
How can I add more hosts to the filter?
If I put this example from the WP Codex in `functions.php`, it stops working.
add_filter( 'allowed_redirect_hosts' , 'my_allowed_redirect_hosts' , 10 );
function my_allowed_redirect_hosts($content){
$content[] = 'blog.example.com';
$content[] = 'codex.example.com';
// wrong: $content[] = '
return $content;
} | Finally it works! What I was doing wrong is putting the code in the WP functions.php file, and not in my custom theme functions.php file.
Thanks all! | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "redirect, wp redirect, wp login form"
} |
Inserting Media to WordPress Posts
If I insert an image to a WordPress docuament via "Add Media -> Insert from URL", and after submitting the URL and inserting to my post, is the image linked to my page or copied to my site?
Thanks. | If you use "Insert by URL" the image is loaded from whatever URL your provide. It is not uploaded to your server at all, nor is any information added to the `postmeta` table as far as I can tell. It seems to be equivalent to simple hand-writing the `HTML` into the post body.
You can pretty much work this out by looking at the page source, but I also tried to search the database of evidence just in case. I did not find any. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, images, urls, media"
} |
Removing customise fields during plugin uninstallation
I created a plugin that insert a field on the customise theme options. Since I use
add_action( 'customize_register', 'myregister' );
to create the customise, should I use
remove_action( 'customize_register', 'myregister' );
when the plugin is deactivated or uninstalled? | The Plugin API has hooks for that:
You can use `register_deactivation_hook` to run a function when the plugin is deactivated.
For uninstall, you have two options. Either `register_uninstall_hook` or add a file called `uninstall.php` in your plugin folder.
I would not recommend delete plugin options on plugin deactivation though, the user might not know that he is losing his saved data. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, customization"
} |
Use wordpress functions in another PHP file
I have created in my theme folder a PHP file named gallery.php. In this file I want to use WP_Query function, but I can't do this because it shows error.
Is possible to do this?
Thanks in advance! | You must put your `gallery.php` in the same theme folder, where the theme's `functions.php` resides. Then add a single line in `functions.php`:
get_template_part('gallery','');
It'll include the `gallery.php` file into `functions.php` and `gallery.php` will behave like `functions.php`.
So, you have to keep in mind that, `functions.php` file is a file for WordPress and PHP functions. So anything out-of-format without proper formatting may occur error into the whole site - and `functions.php` is a core file of any theme.
I don't think it's impossible using `WP_Query()` inside a `functions.php` \- but you have to format and place it properly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, loop, wp load.php"
} |
How can I make use of WP Mobile Detect conditions from within a plugin?
I recently downloaded the WP Mobile Detect plugin and integrated it to my theme (the original mobile detect library I include from the theme folder and the matching WP-functions I pasted directly into `functions.php`).
Now I have one Social Share Plug-In I only want to appear when the site gets requested by desktop devices. So I tried modifying the core files of that plugin, wrapping the output function inside a condition of WP Mobile Detect, like:
if ( ! wpmd_is_phone() ) { // output my share buttons }
Unfortunately, this will return a `Call to undefined function`. How can I fix this? | You either have to include/require the WPMD file that includes the function(s) you are using, or just use the globally defined `$detect` object, like so:
global $detect;
if (! $detect->isMobile() || $detect->isTablet()) {
// output your share buttons
}
**// EDIT**
The above conditional is the equivalent of your `! wpmd_is_phone()` conditional. However, if you want to restrict this to desktop devices only, you should use the following:
global $detect;
if (! ($detect->isMobile() || $detect->isTablet())) {
// output your share buttons
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, mobile"
} |
How to create a word press user with hashedpassword
I have set of user data from another wordpress site and i want o create users for each of them in a another wordpress web site..,it is works fine with `wp_insert_user($user)` but problem is the password is hashed agin..,so i can't log with that login information,so how can i create user with hash password or stop creating hashed password | You would have to update the password column in the database (see below). But this alone won't work. Password hashes are salted using the SALT keys in your `wp-config.php` (this must be kept secret). Your new site would **need to have identical keys** for the password verification to work.
The following function updates a given user's password field (in the database) with the provided (hashed) password:
/**
* @param int $user_id The user ID
* @param string $hashed_password The hashed password
* @return int The number of rows updated (should be 1 or 0 ).
*/
function wpse_update_password_field( $user_id, $hashed_password ){
global $wpdb;
return $wpdb->update(
$wpdb->users,
array( 'user_pass' => $hashed_password ),
array( 'ID' => $user_id )
);
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, login, password"
} |
Edit custom HTML page from WP admin dashboard
I needed to make custom HTML page in root which will not use default wordpress theme and show content and I linked it on menu as custom links. So in front end everything perfect. But this page is not part of wordpress and I am not sure if it will harm SEO or something.
Is there any way plugin or something so text on this pages can be edited from dashboard.
Is there any way so this page to be covered with wordpress sitemap.xml, SEO settings and plugins, and chaching plugins | If you want content to be editable via the dashboard, a static HTML file is not the road you want to take.
Instead, create a custom page template, from which you call a custom header and footer.
Both `get_header()` as well as `get_footer()` take an optional `$name` parameter to specify a specific template to call as well. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pages, html, seo, sitemap"
} |
is there a simple way to list every templates / php files used to generate a specific page?
To customize a theme , it is not always easy to trace every files that are used and find out which one do what . For example i' like to find out how my menu is generated so i can add some conditions to it , and also change the display. Is there a way to find out all the files loaded ? which header is used ...etc... maybe put a bit of code somewhere in the autoload sytem? or using firebug? | WordPress does not really track what theme files are loaded beyond some basic things (for example `$template` global holds main template file).
You can use PHP's native `get_included_files()` to list _all_ PHP source files loaded during request and narrow it down to your theme. Note that for more complex themes this will have not only templates, but likely a lot of framework files as well. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "php, theme development, child theme, customization"
} |
Xml output not places where i want
I have a script that checks status (daily with cron) of some sites and write result in a xml document. Xml is like this :
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<sites>
<site1>result of site1</site1>
<site2>result of site2</site2>
...
</sites>
</xml>
Then i have a function that let me get xml content for each site with wordpress shortcodes , like this :
<?php
function CheckRemoteService($atts) {
extract(shortcode_atts(array(
'name' => 'txt',
), $atts));
$xml = simplexml_load_file('my.xml');
echo $xml->sites->$name;
}
add_shortcode('checkmyurl','CheckRemoteService');
?>
Shortcodes give me the correct output but all results are placed on same row at top , like if are blocked there. I want to insert these results in a table with other data. Is this a xml limit or i have done some mistakes ? Thanks. | Shortcodes must _return_ content and not _echo_ it. See any of the examples in the codex for `add_shortcode()`
So your callback function should probably be:
function CheckRemoteService($atts) {
extract(shortcode_atts(array(
'name' => 'txt',
), $atts));
$xml = simplexml_load_file('my.xml');
return $xml->sites->$name;
}
add_shortcode('checkmyurl','CheckRemoteService'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, xml"
} |
Capability to read/edit page in wp-admin only for administrators
I want to create a page which is only for editable and readable (within wp-admin) for administrators. To restrict other users to edit any page (and not only the own ones) is not the solution as I want them to have this capability.
I am using the plugin called "Access" by wp-types. | Thanks brasofilo!
add_action( 'pre_get_posts', 'hide_pages_to_user_except_admins' );
function hide_pages_to_user_except_admins( $query ) {
if( !is_admin() )
return $query;
global $pagenow;
$pages = array('201','38','99'); //page ids
if(
'edit.php' == $pagenow
&& ( get_query_var('post_type') && 'page' == get_query_var('post_type') )
)
$query->set( 'post__not_in', $pages );
return $query;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, wp admin, capabilities, user access"
} |
listing custom post type category page
I've registered custom post type "deals" and its taxonomy "deals-category"
the page site/deals/ runs the archive-deals.php fine
but in page site/deals-category/travel/ runs the archive.php file!
How can i make site/deals-category/travel/ runs the archive-deals.php or other file ? | Refer to the Template Hierarchy to see why this doesn't work. `archive-{$post_type}.php` is only for custom post type archive display, the format for custom taxonomies is `taxonomy-{$taxonomy}.php`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, archive template"
} |
Call custom post type by category
Ok, I used Custom Post Types Ui to create several custom post types. When setting up the CPT's I checked off that categories were enabled, and then I added a few categories to one of the CPT's. Now I'd like to call one of the categories (upcoming-meetings on a page, but it doesn't seem to be working. Here's my code:
<?php $cpt = get_post_meta($post->ID, "my_meta_box_select", true); ?>
<?php $temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query(); ?>
<?php $wp_query->query("post_type= '.$cpt.'&paged=".$paged.'&showposts=5&cat=upcoming-meetings'); ?>
Any help would be appreciated. I looked around some, but didn't quite understand the difference between Categories and Taxonomies. If anyone wants to shed some light on that for me, that would be great as well.
Thanks, Matt | Most likely, your Custom Post Types are using custom taxonomies that happen to be named "Category". Try something like this:
$args = array(
'post_type' => $cpt,
'tax_query' => array(
array(
'taxonomy' => '[whatever your taxonomy is named],
'field' => 'slug',
'terms' => 'upcoming-meetings',
)
)
);
$query = new WP_Query( $args );
You may be able to find out the taxonomy name from a management screen in the backend. I'm not familiar with the Custom Post Types UI plugin, so unfortunately I can't really help you there.
### Definition
"Taxonomy" is a catch-all term that encompasses WordPress's native Categories, Tags, and any custom taxonomies that you (or a plugin) may create. So "Category" is a type of taxonomy, as is "Tags".
### Reference
`WP_Query` on the Codex | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, categories"
} |
How to link to the page displayed by home.php?
I am working on a theme that is using front-page.php as a front-page.php and home.php to show blog posts. What I can't figure out is how to link to the blog page that is displayed with home.php.
Obviously if I set a specific page to display blog posts in the readings page, I can link to that page, but that doesn't solve the problem. I need a way to link to the page that setting points to. | Ask the option `page_for_posts`:
get_permalink( get_option( 'page_for_posts' ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, templates, template hierarchy"
} |
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';'
I am trying to use following codes to have an email share button in a WordPress website. But adding this codes in single.php shows "Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in .......... in line 72". Please help me someone to fix this issue.
<?php echo "<a href="mailto:type%20email%20address%20here?subject=I%20wanted%20to%20share%20this%20post%20with%20you%20from%20<?php bloginfo('name'); ?>&body=<?php the_title('','',true); ?>%20%20%3A%20%20<?php echo get_the_excerpt(); ?>%20%20%2D%20%20%28%20<?php the_permalink(); ?>%20%29" title="Email to a friend/colleague" target="_blank">Share via Email</a>"; ?> | It's not a very good practice to echo html code. Also you have errors with quotes.
Correct way to do this would be:
<a href="mailto:type%20email%20address%20here?subject=I%20wanted%20to%20share%20this%20post%20with%20you%20from%20<?php echo rawurlencode(get_bloginfo('name')); ?>&body=<?php echo rawurlencode(get_the_title()); ?>%20%20%3A%20%20<?php echo rawurlencode(get_the_excerpt()); ?>%20%20%2D%20%20%28%20<?php echo rawurlencode(get_permalink()); ?>%20%29" title="Email to a friend/colleague" target="_blank">Share via Email</a> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "errors, parse"
} |
Displaying an ACF list of users
I've created a custom field using ACF to display the editors of a page (this may be a comma separated list of a few) including a link to their archive, but all I'm getting is a plain text 'Array'. Could someone help me get this right? For some reason I'm not finding the right info through the documentation.
if(get_field('editor')) { echo ', edited by ' . get_field('editor') . '';}
$values = get_field('editor'); if($values) { foreach($values as $value) {
echo ' ' . $value . ','; } } | You can use `get_author_posts_url()` or `get_the_author_meta()`:
$values = get_field( 'editor' );
if ( $values ) {
$editors = array();
foreach ( $values as $value ) {
$link = get_author_posts_url( $value['ID'] ); //get the url
$nicename = $value['user_nicename'];
$editors[] = sprintf( '<a href="%s">%s</a>', $link, $nicename ); //create a link for each author
}
echo 'Edited by: ' . implode( ',', $editors );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, array, advanced custom fields"
} |
Get a raw value of excerpt
I am trying to print the post excerpt using the following code:
<?php echo $post->post_excerpt; ?>
It works fantastic the only problem is that apparently I get also predefined styles and I cannot get rid of them. How can I get the raw text - is there a different function or maybe there is a php function that returns text only? | Using the PHP strip_tags() function should clean out the unwanted HTML elements.
<?php
echo strip_tags( $post->post_excerpt );
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "excerpt"
} |
What is the condition to check if we are in admin or frontend?
What is the condition to check if we are in admin or frontend?
I want to add_action not in backend, but only in frontend. | Take a look at the `is_admin()` conditional tag:
function wpse106895_dummy_func() {
if ( ! is_admin() ) {
// do your thing
}
}
add_action( 'some-hook', 'wpse106895_dummy_func' );
`is_admin()` returns true, if the URL being accessed is in the dashboard / wp-admin. Hence it's negation (via the not operator) is true when in the frontend.
**Update** , see comments below:
function wpse106895_dummy_func() {
// do your thing
}
if ( ! is_admin() ) add_action( 'some-hook', 'wpse106895_dummy_func' );
will save you overhead. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 10,
"tags": "conditional tags"
} |
How do I make it so that the all users page is not a white screen?
I tried to up the amount of users displayed on the screen, and then after clicking 'Apply', the Users page stays white for me, and only the user page. How do I fix this? | The answer is "Undo what you did", but you did not explain what you did so I am assuming that what you did was change the "Screen Option" value on the `wp-admin/users.php` page. If that is the case, you need to get into the database via PhpMyAdmin or some other tool and change the `users_per_page` value for your user.
You can also add the following to your theme's `functions.php`, load a page, and then remove it.
// change '1' to your user ID
// 20 is the default value so it should set things back to normal
update_user_meta(1,'users_per_page',20); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, users"
} |
Passing dynamic options from backend to frontend
I have created an admin options page (using the Redux Theme Framework), in which the admin can customize the website's appearance (text color, background color, background repeat options, etc.. ).
Let's suppose i want to give my user the possibility of setting a custom background for a section. Admin-side, i have a media uploader form (unique id: my_div_background_url).
In the frontend, I can retrieve this option and then echo it like this:
<?php
$options = get_option('my_theme');
$section_background_url = $options['div_background_url'];
echo '<section style="background-image: url(\'' . $section_background_url . '\');"></section>';
?>
My question is: is this the right and best way to do this? Wouldn't it be better if all of my options were saved in a css file whenever the admin changes them, and then having this file included in my website? Or are there others methods? | By default, options are auto-loaded. So all options with `autoload: yes` will be fetched very early. Your option will not need an additional query.
Also, database access is often faster and more reliable than file access. The options table is also usually included in database backups, and it can be exported in multiple formats. So stick with options.
What you should do: escape the URL. It might have been compromised, so …
if ( ! empty ( $options['div_background_url'] )
{
$section_background_url = esc_url( $options['div_background_url'] );
echo "<section style='background-image: url($section_background_url);'></section>";
}
You could move the custom styles to _one_ `style` element in the `head` element. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes, admin, css, theme options, options"
} |
Custom colors for post rows based on post meta value
I'm trying to have the post background colors change depending on a meta value for the specific post type rather than using the post status. Looked everywhere and can't find a solution. (perhaps there isn't one?)
**Specifying post colors based on post-status is simple enough**
add_action('admin_footer','posts_status_color');
function posts_status_color(){
?>
<style>
.status-draft{background: #FFFF98 !important;}
.status-pending{background: #FFFF98 !important;}
.post-*id here*{background: #FFFF98 !important;}
.status-publish{/* no background keep wp alternating colors */}
</style>
<?php
}
**How do I specify the colors based on a custom meta key/value from the post?** | If your theme uses wp post class
function post_classes($classes) {
global $post;
$customMetaVariable = get_post_meta( $post->ID, 'customMetaName', true );
if($customMetaVariable == 'desiredCustomMetaValue'){
$classes[] = 'cssClassName';
return $classes;
}
}
add_filter('post_class', 'post_classes');
then in your style.css you could use:
.cssClassName{
background-color: red;
}
hence applying that class to all of the posts that contain your desired meta value.
if your theme doesn't use wp post class you have to edit the theme to include
<?php post_class(); ?>
ex:
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
//post stuff hurr
</div>
all explained here. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "posts, functions, admin, css"
} |
Security and Must Use Plugins
From the codex article on Must Use Plugins:
> Can be enabled simply by uploading file to the mu-plugins directory, without having to log-in
This feels like a potential security problem to me. Regular plugins have to be activated via the admin panel before any code from the plugin runs on the site. I always thought this was a sensible security precaution because an attacker who was somehow able to upload a file to the plugins folder would also have to access and modify the database before he could get the code to run. The `mu-plugins` folder seems to provide a simple way to circumvent that.
I know the WordPress devs know a bit more about security than I do, so I was just wonder if someone could explain why this isn't a security hole. | I agree with Wyck's comment. If I can upload files, game over. If I couldn't upload to `mu-plugins` chances are that I could upload, and overwrite, the theme's `functions.php` or Core files instead. Any of those options work as well or better than a `mu-plugin` file would.
The "also modify the database" part is irrelevant because if I can upload files modifying the database is trivial. Just run `wp_insert_user` or use `$wpdb` to run SQL to directly alter the database.
In other words, if I can upload files to the server I have already got more substantial control over the server than PHP is able to deal with, more control than PHP is able to put up a barrier against. The ability to upload to the server is a very substantial hack.
I don't know that activating plugins is so much security as it is convenience. The user can switch plugins on and off, and the developer can use activation and deactivation hooks to run special purpose code. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, security"
} |
Gallery stripped from excerpt of post
I'm having trouble with galleries being stripped/filtered out of the content of the post excerpts before the "read more" click (the galleries load just fine when you click and read the post all by itself on a full page).
Something in the template is stripping that out (there are lots of filters in the theme options, none of which have worked turning them off).
Does anyone know what code to look for that might be stripping something like the standard wordpress galleries? I'm somewhat new to Wordpress and not great at php, so wondering if anyone knew what I should look for.
Side notes: Other templates display it correctly, other gallery plugins do the same thing, there is an extra file content_gallery.php, I don't see any "filters" besides using functions to strip. | Your theme most likely uses `the_excerpt()` function. This function takes the post content and removes all formatting and shortcodes (including the `[gallery]` shortcode), and truncates it to a certain amount of characters.
What you could try is removing this function, and replacing it with `the_content()`, which still respects the `<!-- more -->` tag in posts, but correctly displays shortcodes and HTML formatting. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, gallery"
} |
How to output taxonomy term (incl. link to archive) on author.php?
I have used the excellent tutorial of Justin Tadlock on Custom user taxonomies in WordPress to add a Blog custom taxonomy to both my Posts post_type as well as the user object_type.
In his tutorial Justin then outputs a list of users that share the same (profession) taxonomy.
I on the other hand would like to output the specific term of my Blog taxonomy on the `author.php` archive, together with some other user_meta-fields I already have added to the User Profile.
How would I be able to accomplish this? Ideally it not only outputs the taxonomy term, but also a link to the term archive. | I found my own answer in the Codex.
In my use case scenario:
$blog_terms = wp_get_object_terms( $post->ID, 'blog' );
if ( ! empty( $blog_terms ) ) {
if ( ! is_wp_error( $blog_terms ) ) {
foreach( $blog_terms as $term ) {
echo '<p>' . __( 'Associated Blog: ', 'wys' ) . '<a href="' . get_term_link( $term->slug, 'blog' ) . '">' . $term->name . '</a></p>';
}
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, terms, user meta"
} |
How to share user data across multiple Wordpress websites?
i have 3-4 sites which has content about traveling,and what i want is one site(main site content all the user data and) in all other sites, users can log in to the sites with that data ,how can i achieve that.., | Two methods.
1. Run the blogs as a WP Multisite, since they would all share the same users, plugins, and available themes.
2. If you don't mind premium plugins, WPMUdev has a user sync setup that works pretty well. This is really your only recourse if you don't have a multisite option. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, multisite, login"
} |
How do I add a menu item to a Pods admin menu?
I'm writing a plugin that will send a notification message to an external queue whenever a menu item is clicked. This function is related to some customized data structures I made using the Pods framework.
I'd like to add the menu item under the sub-menu for a certain Pod. The Pod is named "spotlight." Currently the only items in there are "All Spotlights" and "Add New"... I'd like to add a third item below these two.
In the code for my plugin, how do I add an additional menu item under this Pod's submenu? | To add submenu items to a specific Pod's menu, try this:
`add_submenu_page( 'pods-manage-your_pod_name', 'My submenu item page title', 'My submenu item', 'manage_options', 'pods-manage-your_pod_name-my-submenu-item', 'your_callback_function' );`
Do this during the admin_menu action in WordPress, or alternatively do it during the 'pods_admin_menu' action. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, menus, pods framework"
} |
wp-admin produces a 302 redirect to itself
I'm running Wordpress (v3.5.2) in network mode.
Any of the sites which try to access /wp-admin produce a browser error saying there is a redirect loop. A redirect checker tool says the page returns a 302 temporary redirect to the same URL.
I have uploaded a default .htaccess file and the same thing happens.
In cPanel, I have checked Domains > Redirects, and there is no such redirect listed.
I have renamed /plugins to /plugins2, and the issue remains.
In the wp_options table, the site_URL is set to www.example.com, which is correct. This matches the DOMAIN_CURRENT_SITE parameter in wp-config.
Any ideas? | I ended up uploading fresh copies of /wp-admin & /wp-includes, as well as the wp files in the root / directory, which resolved the problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 4,
"tags": "wp admin, redirect"
} |
wp_insert_post() or similar for custom post type
Need to insert custom post type objects from code. Haven't been able to add using the default method
$id = wp_insert_post(array('post_title'=>'random', 'post_type'=>'custom_post'));
creates a regular post instead. | From the Codex:
> wp_insert_post() will fill out a default list of these but the user is required to provide the title and content otherwise the database write will fail.
$id = wp_insert_post(array(
'post_title'=>'random',
'post_type'=>'custom_post',
'post_content'=>'demo text'
)); | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 8,
"tags": "custom post types"
} |
Child theme template value for style.css for parent in different folder
I am making a child theme in the `.../wp-content/themes/` folder however the parent theme that I am building on is in the `.../wp-content/plugins/` directory. I am able to import the parent `style.css` file using a directory path but when I try to do the same for the Template value, it does not work. Similarly, the simple name of the parent theme folder does not work either, presumably because the parent theme is in a different directory.
Any ideas on how to fix this? | If the parent theme's non-standard location was correctly added with `register_theme_directory`, and I am pretty sure it must have been, then functions like `get_stylesheet_directory_uri` and `get_template_directory_uri` should work.
# Reference
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "child theme"
} |
How do you modify Page Template?
Do I just go to Appearance->Editor and then pick the template and modify the PHP code directly, or is there a more "non-coding" way of doing it?
I'm using a theme with a contact form, and the whole contact form code is in the template, and the edit page window just shows up blank. All the code is in the template. | All code will be in the template. That is how custom templates work.
Altering the output those templates is a code edit except where the templates have been written to include the post body, or meta fields, etc.
But _don't_ go to `Appearance->Editor` and start hacking away. First, if this isn't your theme you are going to have to redo the work when you update the theme, and second, if you make a mistake in the built in editor you can take the whole site down and not be able to get back in to edit the file. I consider that editor the equivalent of working on an airplane while it is in the air.
Instead, grab the file via FTP, edit it is a _text editor_ , preferably one intended for code, then reupload it. Ideally, you'd set up a development server on your computer so that you can not only edit but test the changes before pushing them live. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates"
} |
3 different ways to check the number of pages on site gives 3 different answers
I entered this command into Google:
site:g33ktalk.com
And it returned 659 pages.
But when I created a sitemap with this service: < it showed me 498 pages crawled.
And when I made the sitemap with the Wordpress default sitemap generator, it showed under 400 pages.
Would anyone know why this happens and what is the correct count? Is it a crawling problem? If so, how would I begin debugging it so that all 600+ pages can be crawled?
Thank you! | Possible mistake: depends on what you mean by 'page'. Search engines would count archives pages as pages, whereas WordPress will only count post-type page, not archives nor posts. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sitemap, google xml sitemaps"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.