INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Inherit plugin settings to new site in Multisite
I use the Breadcrumb NavXT plugin for a WP Multisite. I activated the plugin for all sites so I can use it throughout my network.
My problem is that every time I add a new site I have to change the default settings of the plugin, but I’d like WP to use the settings I already customized for the main site because on all future sites they would be the same.
Is there a way to force WP adopting the plugin settings of the main site? | Nice Question!
But I'll leave for the asker and for the reader the task of **finding the plugin options name**.
This can be used for any plugin/theme that relies in a _single/serialized_ value in the `wp_options` table. If it's not a single value, it's another task...
In this example, I'm using WP-Pagenavi `option_name`.
!wp-pagenavi option name
_Action hook found inside the function`wpmu_create_blog` in the file `/wp-includes/ms-functions.php`._
add_action( 'wpmu_new_blog', 'wpse_70977_copy_main_site_options', 10, 6 );
function wpse_70977_copy_main_site_options( $blog_id, $user_id, $domain, $path, $site_id, $meta )
{
$mainsite = get_option( 'pagenavi_options' );
switch_to_blog( $blog_id );
update_option( 'pagenavi_options', $mainsite );
restore_current_blog();
}
This code is tested with the plugin being activated on a per site basis, and with the plugin being Network Activated. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "plugins, multisite, options"
} |
prevent caching during tinymce custom button development
I'm following this turial on how to add a custom button to TinyMCE editor in WordPress. Trying to edit author's JS to include my functionality, yet it seems to have gotten cached. Article author has a hack for it (code snippet below), and it did work for the first time (the button is in the toolbar now), although it doesn't work for subsequent refreshes.
// "This will intercept the version check and increment the current version number by 3.
// It's the quick and dirty way to do it without messing with the settings directly..."
function my_refresh_mce($ver) {
$ver += 3;
return $ver;
}
add_filter( 'tiny_mce_version', 'my_refresh_mce');
What can I do to **disable the caching**?
Latest fresh WordPress localhost install, no plugins activated. | Turns out the 'no plugins activated' was not enough. Once I did a completely fresh install ( **without** W3 Total Cache plugin), the issue disappeared. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tinymce, post editor, plugin tinymce"
} |
Change success message in plugin Theme my login
I am using theme my login plugin and want to replace message when people registered and it's redirect back to login page with displaying message at the top of the form.
**Message:** `Your registration was successful but you must now confirm your email address before you can log in. Please check your email and click on the link provided.`
I want to replace this message. | The below should work as is (with your strings for the new message and the theme's text domain), when inserted in your theme's _functions.php_ :
function wpse71032_change_tml_registration_message( $translated_text, $text, $domain ) {
if( $domain === 'theme-my-login' &&
$text === 'Your registration was successful but you must now confirm your email address before you can log in. Please check your email and click on the link provided.'
) {
/* in the below, change the first argument to the message you want
and the second argument to your theme's textdomain */
$translated_text = __( '%Registration Message%', 'theme_text_domain' );
}
return $translated_text;
}
add_filter( 'gettext', 'wpse71032_change_tml_registration_message', 20, 3 );
See the article on the gettext filter in the Filter Reference. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "plugins, login"
} |
Removing custom post type from link search results
I have created a custom post type and disabled it from appearing in search results. However when I add a link from a normal post, I still get these entries from my custom post type available to link to in the internal linking box (at the bottom when of the popup when you click the link button in the editor). How can I disable the custom post type from displaying entries there as well? | I suggest making it private (`'public' => false` when registering the post type). You could club it with `'show_ui' => true` to still display the admin interface.
See the codex for `register_post_type` for full reference < | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "custom post types, links"
} |
Apply permissions per post
We have a WordPress site where we have external authors for whom we have created usernames at the `Editor` level. We want these editors to be able to create new posts and modify their own posts, but occasionally we have posts in progress that we'd rather keep more private.
It is a very small pool of users, and an even smaller number of posts to "protect," so I am okay with any technique that requires explicit GRANT for our own users or explicit DENY for the external users. DENY would be easier of course, but I am not going to get fussy. | If you look at Wordpress's explanation of Roles and Capabilities, you will see that the correct role you should have assigned them is Author.
That being said, if you for some reason don't want to change them to Authors, you can alter the capabilities that a role has. See the full list of Editor capabilities here.
remove_cap( 'editor', 'read_private_posts' );
remove_cap( 'editor', 'edit_private_posts' );
remove_cap( 'editor', 'delete_private_posts' );
This will permanently remove that capability, so after the wp-admin of the site is loaded once, you can remove these lines or comment them out. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "admin, permissions"
} |
get a specific taxonomy term name
I need to print a specific term with its id. I get that for categories with this code:
<a href="<?php echo get_category_link(1); ?>" title="<?php echo get_cat_name(1);?>"><?php echo get_cat_name(1);?></a>
… where 1 is the id I have to print. Is there something like the following?
<?php echo get_term_link(1); ?>
or
<?php echo get_term_name(1); ?> | Use `get_term()` to get the name, slug, or description:
$term = get_term( 1, 'taxonomy_slug' );
// Name
echo $term->name;
// Link
echo get_term_link(1, 'taxonomy_slug');
// OR
echo get_term_link( $term ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "taxonomy, terms"
} |
How can I change the link in comment form "Log in to post a comment"?
Right now there is a link and I am using a plugin for a modal box and I would like to change the link in the code.
Where is the html and php file with the code located?
I have looked in my theme files, but comments.php do not contain the code I need to change.
Can I hack it via functions.php hook? | the link is called from within `comment_form()` (/wp-includes/comment-template.php line 1539) :
'must_log_in' => '<p class="must-log-in">' . sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
and uses `wp_login_url()` (/wp-includes/general-template.php lines 224+) which uses a filter on its return:
return apply_filters('login_url', $login_url, $redirect);
you might be able to add a filter function to functions.php of your theme, to influence the link; example:
add_filter( 'link_url', 'wpse_71100_linkchanger');
function wpse_71100_linkchanger( $link ) {
/*whatever you need to do with the link*/
return $link;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "comments"
} |
How to redirect a page to subdomain?
I have a blog on wordpress say example.com with a page name "mypage" in it. When a user clicks on mypage I want him to redirect to mypage.example.com (a subdomain that I have already created) inspite of opening example.com/mypage. I want my page to redirect to my subdomain.
I am a user of wordpress and hence I dont know much about how to do it. Please help me out on it, I would be really thankfull. | Can you use a custom menu ( **Appearance** -> **Menus** ) ? If so, just create a custom link and insert it where desired. This has the added benefit of not cluttering your list of pages with a page that isn't real. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "pages, redirect, subdomains"
} |
list author's posts in author.php
I want to list 10 last posts of author in author.php template. I used this code:
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
But I can see only the last post of current author. Any help? | The easiest way would be to simply add:
global $query_string;
query_posts( $query_string . '&posts_per_page=-1' );
just before your code so you get :
<?php
global $query_string;
query_posts( $query_string . '&posts_per_page=-1' );
while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile;?> | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "author"
} |
How to speed up my site
> **Possible Duplicate:**
> Steps to Optimize WordPress in Regard to Server Load?
I've got a WordPress site with a few plugins installed, and it takes a long time to load.
I'm concerned about this; I don't want visitors just giving up and leaving, also Google takes page speed into account in its Page Rank.
Is there a way I can speed up my site without removing any of my plugins? | Try using a caching plugin. There's plenty available, the two most popular being WP Super Cache and W3 Total Cache. If you're just starting out with caching, I'd recommend W3 Total Cache, as it is rather easy to set up and includes a lot of options. It's even used by some of the bigger sites such as iPhoneClub.nl, The Next Web, and Digital Trends. [source]
Normally each time someone visits your site WordPress has to dynamically build the page by making database queries and loading theme template files. A caching plugin saves the output as a static HTML file, and serves that to your visitors instead. Each time you modify your site or write new content, you need to empty the cache and the plugin will start building HTML files again. This saves a great many database queries and requests.
One last thing: if you have restrictive resource limits, or you happen to use the BuddyPress plugin, I would instead recommend Hyper Cache, as it's specifically built for that purpose.
Happy caching! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "cache"
} |
Clean install - Changing permalinks in twentyeleven give 404
interesting problem that I encountered, not sure if it's bug or not..
On a clean install using the **twentyeleven** theme I try changing the _Permalink Settings_ to something different from the _Deffault_ and every post starts giving Page Not Found 404. The Pagination and the top Nav Menu also stop working.
What needs to be changed for all of this to start working, because the same problem is present when I start creating custom theme?
EDIT: Figured it out! The solution was very simple - turning the _rewrite module_ of WAMP. | Check to make sure your .htaccess file (in the root) is writable by WordPress, if it isn't then you may need to manually set this up to get the permalinks working correctly. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "permalinks, pagination, 404 error, theme twenty eleven"
} |
Wordpress wont startup
So far I've narrowed down the execution trail to
`index.php` -> `require('./wp-blog-header.php');` ->
if ( !isset($wp_did_header) ) {
require_once( dirname(__FILE__) . '/wp-load.php' );
->
if ( file_exists( ABSPATH . 'wp-config.php') ) {
require_once( ABSPATH . 'wp-config.php' );
-> `require_once(ABSPATH . 'wp-settings.php');` -> `wp_not_installed();`
The execution doesn't get any further than this and I can't find where `wp_not_installed()` is defined. I don't know why it's led up to that method/function in the first place because I've already installed and set Wordpress up. Any help appretiated... | Setting the `max_execution_time = 300` inside my `php.ini` resolved it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "troubleshooting"
} |
Change featured image urls in database
Im storing my images on another server and Ive managed to change the urls in the database but I cant seem to change the featured image urls?
I will not be adding any more images so I just want to change the url for all images.
This is the sql I used for normal images
UPDATE wp_posts SET post_content = REPLACE (post_content, 'src=" 'src="
and
UPDATE wp_posts SET guid = REPLACE (guid, ' ' WHERE post_type = 'attachment';
All the other images are fine except the featured images. | The featured image is stored in the `*_postmeta` table under the `_thumbnail_id` key. In fact, chances are that you've got a lot of image/media urls in that table, which you haven't changed. The problem is that a number of things are stored in serialized arrays and changing them with SQL as above will (probably) break those arrays. I would suggest using something like Velvet Blues Update Urls.
It looks like you have changed all of your URLs and not just the image/media URLs. Is that what you intended?
Also, you should never change the guid.
NOTE and EDIT: I just noticed an exception for attachment media in the WordPress Codex. I don't remember ever seeing that and I am not sure what that is about and I am not sure what to make of that at the moment. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "post thumbnails, mysql"
} |
Does wordpress have an error log?
I accidentally removed a bunch of plugin folders. I restored them all directly after, but since then my site is completely blank. Can't see anything, it's just white.
I'm not sure what to do, but looking at a log file seems like a good start. Is there one? | There's not one if you didn't set one up. The codex has a good example of how to do this.
<?php
@ini_set('log_errors','On');
@ini_set('display_errors','Off');
@ini_set('error_log','/home/example.com/logs/php_error.log');
/**
* This will log all errors notices and warnings to a file called debug.log in
* wp-content (if Apache does not have write permission, you may need to create
* the file first and set the appropriate permissions (i.e. use 666) )
*/
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);
White screen of death is usually caused by WordPress looking for the active theme and not finding it. If you can access the admin area, got to Appearance > Themes and reactivate your theme. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "errors, fatal error"
} |
Multiple og:image for Facebook
I've actually been searching on this site for the answer to this question for quite some time. Looking for a way to 'echo/print' multiple og:images for facebook. What I have here used only 'the_post_thumbnail'
function fb_image() {
if (is_single()) {
global $post;
$feature_image = get_the_post_thumbnail($post->ID);
$doc = new DOMDocument();
$doc->loadHTML($feature_image);
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
$image_url = $tag->getAttribute('src');
}
}
?>
<meta property="og:image" content="<?php echo $image_url; ?>" />
<?php }
add_action('wp_head', 'fb_image'); | Figured it out with
function postimage($size = 'thumbnail', $qty = -1)
{
if (is_single() && !is_home() && !wp_attachment_is_image()) {
global $post;$images = get_children(array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'posts_per_page' => $qty,
'post_mime_type' => 'image')
); if ( $images ) {
foreach( $images as $image ) {
$attachmenturl = wp_get_attachment_url($image->ID);
$attachmentimage = wp_get_attachment_image( $image->ID, $size );
echo '<meta property="og:image" content="'.$attachmenturl.'"/>';
}
} else {
echo "No Image";
}
}
}
add_action('wp_head', 'postimage'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "facebook"
} |
single.php - how to mark current page in the loop
I am using the following loop on `index.php`.
The current viewed page would be one of the link in the loop.
**How to make sure it is marked as current?**
<ul id="questions" class="subpage">
<?php
$index_query = new WP_Query( array( 'post_type' => 'faq', 'orderby' => 'modified', 'posts_per_page' => '-1', 'order' => 'DESC' ) );
while ( $index_query->have_posts() ) : $index_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php echo get_field('short_version'); ?> »</a></li>
<?php endwhile; ?>
</ul>
`get_field()` is a function from Advanced Custom Fields and has the following format:
`get_field($field_name, $post_id);` | Here's a rewritten version of your code
<ul id="questions" class="subpage">
<?php
$current_id = get_the_ID();
$index_query = new WP_Query( array( 'post_type' => 'faq', 'orderby' => 'modified', 'posts_per_page' => '-1', 'order' => 'DESC' ) );
while ( $index_query->have_posts() ) : $index_query->the_post();
if(get_the_ID() == $current_id)
echo 'this post has the same ID as the current global one';
?>
<li><a href="<?php the_permalink(); ?>"><?php echo get_field('short_version'); ?> »</a></li>
<?php endwhile; ?>
</ul>
Please note that on the index.php you can have queries of single post types as well as of archives(depending on your theme). If in case of an archive this will match the first post of that archive only. If you want to match for other types of templates, please see the conditional tags | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "loop"
} |
does acf_save_post cause endless loop?
I am using Advanced custom fields `acf_save_post` hook in one of my functions. In that function I use the `add_post_meta` function. Does this call `acf_save_post` again and cause an endless loop?
< | `add_post_meta` doesn't call the same hook again but there are some other functions such as `wp_update_post` which call the hook again. In case it is going into infinite loop you'll have to call `remove_action` inside the function to not make it recursive | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, save post, advanced custom fields"
} |
Does WordPress Change the .htaccess File When Updating?
I've just implemented a new WP website, replacing an older hardcoded HTML site. I will be adding 301 redirects in the `.htaccess` file to point the old URIs to the new WP Permalinks.
My questions is, as WP generates the `.htaccess` file initially (at least on my install it did) will WP overrite the `.htaccess` file when I update WP in the future?
Further to the above, is there any time, including the update as mentioned above, that WP may overwrite this file and if so is there a way to prevent that?
I've searched high and low and can't seem to find a straight answer.
Any help would be appreciated.
Thanks! | Generally speaking WordPress will update the .htaccess file any time you change the permalink structure. Many plugins will also update/modify the file as needed.
But the default structure of the .htaccess file allows you to lay it out in such a way that WordPress will not overwrite your custom entries.
WordPress will overwrite the entries between '# BEGIN WordPress' and '# END WordPress'. While most plugins will create their own begin and end tags and only update within those tags.
Simply put your custom entries outside of any custom tags/comments and they _SHOULD_ be preserved when WP updates the file. | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 7,
"tags": "permalinks, htaccess, updates"
} |
Template for slug
I am using the "Edit Author Slug" plugin to provide public profile pages on my site using the following structure: **mysite.com/users/username**.
Now, I want to show a list of all users on **mysite.com/users/**. But this returns a 404 because the "users" path is only a slug created by the plugin.
Does WP provide the possibility to create slug templates (just like tag templates)? Or is there another way to accomplish this?
Thanks for your help :-) | Try creating a Page with the users slug, then using a custom Page Template to provide the functionality you want to display all the users. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "templates, slug"
} |
How do I duplicate a single post, with all its properties, and save it as a different post?
In a wordpress plugin, how can I duplicate/clone a single post?
I would need to: 1) get a specific post 2) clear its ID property so that it's saved as a new post 3) save it.
In the process, I would like to see all the meta info + taxonomy associations preserved. | Take a look at the 'Duplicate Post' plugin at < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, wp admin"
} |
Remove Query String from Google jQuery
Was wondering if anyone knew of a way to remove the query string from external Javascript sources, such as Google's jQuery. Thanks in advance for any help | Filter `'script_loader_src'`, you get the source URL as first argument. Then run `remove_query_arg()` on this URL and return the shortened version.
Sample code:
add_filter( 'script_loader_src', 'remove_script_version_parameter' );
function remove_script_version_parameter( $src )
{
return remove_query_arg( 'ver', $src );
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "google"
} |
Why would changing a child theme to a normal theme pass a Template is missing. error
I have what used to be a child theme but I added to it to the point where its a theme on its own. I pulled out the Template line in the style.css and now I get the: This theme is broken. Template is missing. error.
Why is this happening? | That error appears when the theme directory has no "index.php" file. For a full theme, an index.php file is required. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, child theme"
} |
How do I create a NextGen slideshow to show all photos?
I have tried many plugins to create a slideshow out of photos I have uploaded to my NextGen galleries. Specifically, I want this slideshow to incorporate photos from all of my galleries. However, so far, the plugins I have encountered only allow for the photos in the slideshow to come from one gallery (as specified by an id argument).
How do I do create a slideshow that has all of my photos in all of my NextGen galleries? I have assigned a tag to each of my photos in NextGen if that helps. | If you look at the nextgen gallery slideshow widget you will find the option "select gallery" => "all images". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin nextgen gallery"
} |
child theme - moved files from twentyeleven theme to child them, now not working
I'm trying to create a child theme.
I copied the files from my twenty eleven theme into my twenty eleven child theme folder, and now the webpage displays blank page.
my dashboard settings changed after I created the child theme that is why I decided to copy all files from main theme to child theme folder.
what should I do? | If you just copy all the files it will never work, the reason being that the functions.php file is included from both parent theme & child theme resulting in re-defining of a few functions(which is a php error)
Don't copy the functions.php file, copy all the other files & modify the few lines at the top of style.css as explained in the codex | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "child theme"
} |
wp_remote_get vs. fetch_feed ? which is the better for performance?
I m trying **to share my web site contents** for other web sites using by external loop file or rss file.
when i asked some questions about `wp_remote_get` function ; @Serkan suggest to me , using `fecth_feed` methot / function etc. (check the question here.)=
I really confused , which one i should, which one is better way for high performance, could anyone explain it why ?
Thanks. | Neither are high performance, and they do different things.
`fetch_feed` is for grabbing feeds RSS feeds etc, `wp_remote_get` is for grabbing arbitrary items.
Neither are fast, and the performance difference between each is negligible or irrelevant, but technically `fetch_feed` is slower than `wp_remote_get`, not because it's faster or slower at grabbing over the network, but because it uses SimplePie to parse the feed ( which you'd end up using anyway if you used `wp_remote_get` on a feed ).
So even using `wp_remote_get`, you'd get the Feed in the same amount of time, but then you'd have to write the code to process it afterwards, and I'm sure the SimplePie people will be faster as they've had more time to optimise and test than you.
So if you're grabbing an RSS or Atom feed, use `fetch_feed`
If you're grabbing html files, images, or other files, use `wp_remote_get`
Why don't you use one of the feed aggregation plugins instead of reinventing the wheel? | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "feed, wp remote get"
} |
Different templates for parent and children categories/taxonomies
I would like to know what is the best way to create a different template for parent and children categories and/or taxonomies.
Example: I have a taxonomy called region, which I want to divide in countries, and cities inside countries. So, I will have a parent taxonomy term called Italy, and it's children taxonomy terms, Rome, Milan, Napoli, whatever. Is it possible to have different templates for country and city? How can I achieve this? Thanks in advance. | I suggest creating 3 files
1) regiontemplate-country.php
2) regiontemplate-city.php
These 2 will contain the templates for country & city, then
3) taxonomy-region.php
In this file, add the code to load the appropriate template
<?php
$term = get_term_by('slug', get_query_var('term'), 'region');
if((int)$term->parent)
get_template_part('regiontemplate', 'city');
else
get_template_part('regiontemplate', 'country'); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "categories, custom taxonomy, templates, template hierarchy"
} |
Can't understand why sometimes a [caption] field appears
I'm trying to make a php script which, given a post id, returns post content. I'm not the one who writes articles, I'm just operating on a wp site. Post content is for an app of mine which has to parse it.
My script is very simple:
<?php
require_once("wp-load.php");
if(isset($_GET['id'])){
$post_id = $_GET['id'];
$queried_post = get_post($post_id);
echo $queried_post->post_content;
}
?>
Result is the article but sometimes the image is embedded in a [caption] field, like this:
[caption id="attachment_78971" align="alignnone" width="276"]<a href="href" rel="attachment wp-att-78971"><img class="size-medium wp-image-78971"/></a>[/caption]
other times I have just the image
<img ...ecc
why is that? Is there a way to force the same output regardless of who has written the article? | The `[caption]` part shows up because one of your authors/editors added a caption to the image when it was inserted into the post. You will have this problem not only with captions but with any other shortcodes that your authors/editors use. And you should be aware that WordPress includes several in its Core but various plugins and even themes provide a lot of them. You will need to process the shortcode:
echo apply_filters('the_content',$queried_post->post_content);
Or strip the shortcodes:
echo strip_shortcodes( $queried_post->post_content );
Which you do depends on the results that you want.
You should also be aware that echoing raw post content-- ie. `$queried_post->post_content`\-- will probably not give you the formatting that you expect, because raw post content is not typically complete markup. Running the `the_content` filter, as above, sorts out most of that. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, wp query"
} |
include shortcode values in Thickbox form
I have a shortcode that is built using a Thickbox form with various inputs that return the values. This works fine. However, I would like the existing values (if present) to re-populate the form if the user opens it again.
**Here is an example of my shortcode:**
`[schema type="person" name="Andrew Norcross" description="I make interwebs" ]`
**I have a working jQuery match function to find the shortcode if it exists:**
`var code = $('div#wp-content-editor-container textarea').text().match(/\[schema(.*)\]/g);`
the code above does get the entire shortcode as a string, but I'm at a loss for how to process it efficiently to get the values I want.
**so what I want to accomplish:**
1. check for a specific part inside the shortcode data (i.e. name="Andrew Norcross")
2. get the value inside the quotes and insert it into the field on the form
I've tried a few ways but nothing seems to function as expected. | Try something like this...
var code = $('div#wp-content-editor-container textarea').text().match(/\[(schema.*)\]/);
code = '<' + code[1] + '>';
alert($(code).attr('description')); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, shortcode, thickbox"
} |
How to get grandparent of a given category
Just wondering what the best way to get the top-most level category (grandparent) of a given category assuming it has one?
Example structure:
Operating Systems \- Mac \- - Mountain Lion \- Windows \- - Windows XP
I want to be able to somehow get the ID of the "Operating Systems" category from within the Windows XP category.
Any suggestions? | You could write a simple function to do this each time you need to. Here's an example I found on this website.
function pa_category_top_parent_id( $catid ) {
while( $catid ) {
$cat = get_category( $catid ); // get the object for the catid
$catid = $cat->category_parent; // assign parent ID (if exists) to $catid
// the while loop will continue whilst there is a $catid
// when there is no longer a parent $catid will be NULL so we can assign our $catParent
$catParent = $cat->cat_ID;
}
return $catParent;
}
Then you can use this function anywhere like so:
$catid = get_query_var( 'cat' );
echo pa_category_top_parent_id( $catid );
Reading the comments in the code it is pretty self-explanatory. Hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
How to pull user/author profile data in a plugin?
My site has a user profile page. For some reason I would like to pull user profile data in my plugin.
I know I can pull logged in user profile data using `get_currentuserinfo();`.
For example I would like to get displayed profile user id.
Can anyone tell me how to pull it.? | If you're trying to get user data for the displayed profile, you can do it like so:
`$thisauthor = get_userdata(intval($author));`
That'll return an object filled with everything you need. For instance, if you need the user ID, you can call it like so:
`$thisauthor->ID`
I use this extensively on the profiles on my site: <
**UPDATE**
In a plugin, it looks like you need to call the global variable first, like so:
`global $author; $thisauthor = get_userdata(intval($author));` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, user meta, profiles, author template"
} |
What is the scope and persistence of add_filter() and remove_filter()?
I understand that using add_filter() or remove_filter() directly within a themes' functions.php would make the changes global across the theme unless you override them elsewhere. But believe this is a result of WordPress initialization.
add_filter( $tag, $function_to_add, $priority, $accepted_args );
However if a call to add_filter() or remove_filter() is made within a function or class:
function example(){
...
add_filter( $tag, $function_to_add, $priority, $accepted_args );
...
}
What is the scope and persistence of the change? | It is always global. `add_filter()` and `add_action()` are just wrapper for the global variable `$wp_filter`. So it doesn’t matter where the function is called.
The same is true for `apply_filters()`, `apply_filters_ref_array()`, `do_action_ref_array()` and `do_action()`: they work in the global namespace, that’s the reason why the callback handlers (functions or methods) have to be public. A protected class method cannot be called from the global scope. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters"
} |
How to disable `SQL_CALC_FOUND_ROWS`
> **Possible Duplicate:**
> wordpress query causing load
In the site I'm trying to optimize, I noticed several queries that are rather slow and start with **`SELECT SQL_CALC_FOUND_ROWS`**
Searching this site, the relevant question **wordpress query causing load** has no adequate answer, in my opinion.
Can I somehow disable `SQL_CALC_FOUND_ROWS` without breaking too many things - if possible breaking nothing? It seems that pagination relies on this.
@Wyck advised me to read this core ticket: **#10964**. After reading it, I can't really understand if the ticket been completely resolved, it seems not.
In any case, is there a way to disable `SQL_CALC_FOUND_ROWS`? | First should only disable `SQL_CALC_FOUND_ROWS` if you aren't using pagination, to do so set parameter `no_found_rows` to `true` in WP_Query.
WP_Query( array( 'no_found_rows' => true ) );
**Note** `get_posts()` does that by default. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "mysql, core"
} |
Subscribe to author?
Basically, I want to follow the author by other WordPress users. Whenever an author posts new post subscribed users need to get notification by email.
If it's not already there, I can create a plugin for this. But I need an idea to store the data. Should I go for custom table or is there a better way to store default table structure. | I have developed plugin called Wp Subcribe Author to subscribe author by email. You can download and use it from WordPress site.
I used custom custom table structure, I feel that's good, because I don't want to mess up with database performance ! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, database, users"
} |
Add Option if Not Exists
I need to see if an option, and if does, get the value. If not, I need to add it.
The Codex provides:
<?php
$option_name = 'myhack_extraction_length' ;
$new_value = '255' ;
if ( get_option( $option_name ) != $new_value ) {
update_option( $option_name, $new_value );
} else {
$deprecated = ' ';
$autoload = 'no';
add_option( $option_name, $new_value, $deprecated, $autoload );
}
Which supposedly **updates the option name myhack_extraction_length with the value 255. If the option does not exist then use add_option and set autoload to no.**
However, it seems to me that the second half could be called in two ways, if the option does not exist OR if the new value==the option
Is this correct? | The logic on the IF THEN ELSE does seem a bit wonky. If I'm reading it correctly...
The call to get_option( $option_name ) will return FALSE if the option does not exist or if it has no value.
So the _IF_ would be executed:
1. when the option doesn't exist and $new_value != FALSE
2. the option has no value and $new_value != FALSE
3. the option exists and has a value that is != $new value
The update_option() call would then update the value or create the option with $new_value.
The _ELSE_ would be called if:
1. the option exists and has the same value as $new_value
2. the option does not exist and the $new_value == FALSE | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 8,
"tags": "codex, options"
} |
How can I make image linking to attachment page (rather than a direct link)?
I currently have the Modern Style Theme installed.
If you click on an image on my page, it links directly to the highest resolution version of that image. (Example post with one image)
I would rather like it to link to an "attachment page", where the description of the image is also showen. How can I do that? | When you insert a new media, you get to choose the **Link URL**. Under the field, there are 3 buttons, simply click **Attachment Post URL** to link to it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images"
} |
show category in woocommerce
This code show tags from a specific category such as id = 3. I want to make automatically check which category I am. Can someone please help me ?
$args = array('categories'=> '3');
$tags = get_category_tags($args);
$content .= "<ul>";
foreach ($tags as $tag) {
$content .= "<li><a href=\"$tag->tag_link\">$tag->tag_name</a></li>";
}
$content .= "</ul>";
echo $content; | within a category you can use `get_queried_object()` to get data on the current category.
$current_category = get_queried_object();
$args = array( 'categories' => $current_category->term_id );
$tags = get_category_tags( $args ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, plugins"
} |
Show Posts to Author Only
I've developed invoicing system in WordPress for one of my website. I've used custom post type with custom meta field, integrated payment gateway to meet my needs. User generally generate invoice to upload fund. I've used a post submission from in frontend so that user can create an invoice by himself. Everything is running smoothly but one invoice created by an user is visible to other users. Ex. A created invoice, id: APL-2012110489586. User B can access the invoice by typing domin.com?invoice=APL-2012110489586. Now I want to restrict the invoice to be accessed from other user. Only admin and invoice creator can access the invoice. All users are in subscriber role. Need your guideline to perform this job. | In your Loop, whether for a 'single' page or an 'index' page, check the post author against the current user ID, and only display the post if they match. Assuming you are using a typical WordPress Loop, something like...
global $current_user;
get_currentuserinfo();
// start of the Loop
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
if ($post->post_author != $current_user->ID) continue;
This also assumes that you are inserting your Custom Post Type entries correctly so that all of the data is populated as it should be. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Exclude Specific Categories?
the code I'm currently using to display categories is `<?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' ';}?>`
I would like to exclude a category called "home-featured" or the category with ID "65" how would I add this to the code above? | You could do it like this:
<?php
$exclude = array( 'home-featured' );
foreach( get_the_category() as $category ) {
if ( ! in_array( $category->cat_name, $exclude )
echo $category->cat_name . ' ';
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
link a custom page into menu
Ok i have a file which named,
page-allpost.php
now I have a menu item called "all post" and in that menu I want to call the page-allpost.php which will display all the post. how to do that?
hope someone here could help, thanks. | Give the file a template header, then create a page under Pages in admin, and assign that template to the page. You can then add that page you created to your menu. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, page template"
} |
Thesis 2 custom Page
I have been installing lately the latest version from Thesis and getting to the point to make a custom landing Page. I have been building a plugin and I would like to link the content of it to my newly created landing Page. How do I do this, where can I upload my custom php code for the thesis landing Page?
thanks in advanced | You can hook from the custom.php file inside /wp-content/thesis/skin/skin-name/
Or you can use this box < to write PHP codes directly inside Thesis skin editor. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, pages"
} |
Adding a custom field or metabox to the post-thumbnail widget?
Is it possible to add a custom field to an existing "widget" in the backend?
What I wanna do is provide a way to have a checkbox to apply a thumbnail that is double the size of the normal one on the frontend. So I'm thinking of simply adding a custom field as a checkbox that says "Double the size" and when checked I return a different output on the frontend.
That is not the problem, I know how to do so.
However I wonder if it possible to locate this checkbox in the post-thumbnail widget in the backend?
!enter image description here
Normally when adding a custom field it appears underneath the excerpt or content area. Is it possible to locate this checkbox inside the post-thumbnail widget?
Thank you in advance | Just filter `admin_post_thumbnail_html` and append your checkbox HTML:
add_filter( 'admin_post_thumbnail_html', 'wpse_71501_thumbnail_options' );
function wpse_71501_thumbnail_options( $html )
{
return $html . <<<html
<p>
<label for="big_thumbnail">
<input id="big_thumbnail" name="big_thumbnail" type="checkbox" />
Use big thumbnail
</label>
</p>
html;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom field, metabox, post thumbnails, thumbnails"
} |
Getting RID of thickbox!
I want to get rid of the complete thickbox css js and loading gif. Can anybody give me the correct way to get rid of it all via functions.php ?
Cheers, Alex | I'm guessing front end only, right?
function wpse71503_init() {
if (!is_admin()) {
wp_deregister_style('thickbox');
wp_deregister_script('thickbox');
}
}
add_action('init', 'wpse71503_init'); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "functions, thickbox"
} |
How to get all post except particular category without breaking the paging
I'm trying to get all post except particular category this works fine but it cause the pagination button/link to render the same posts again on page 2, 3, 4 and so on not rendering the older post. Here is how I am trying to exclude a particular category
<?php query_posts('cat=-22');?>
This excludes the category but prevents pagination buttons/link from showing older posts, instead it shows the same first 5 posts as on page 1.
I tried moving the category exclusion bit into the `<?php if ( have_posts('cat=-22') ) : ?>` line but this doesn't change anything.
I'm trying to do this on the `index.php` and `archive.php`
I've also tried excluding the category by its name and I get the same results. | I would filter `pre_get_posts`. Perhaps like so, though you may need to tweak the conditional a bit:
function wpse71508_filter_pre_get_posts( $query ) {
if ( is_main_query() ) {
if ( is_home() || is_archive() ) {
$query->set( 'cat', '-22' );
}
}
return $query;
}
add_action( 'pre_get_posts', 'wpse71508_filter_pre_get_posts' );
If you could clarify the _context_ (rather than the _template file_ ) to which you want to apply this query modification, I can be more specific. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query, query posts"
} |
Adding a content rating system
I run a multiple author site and the content is directed to various age groups. Instead of forcing the writer to manually note which age group the post is appropriate for, I want to add a content rating system with the following labels:
> G — Suitable for all audiences
>
> PG — Possibly offensive, usually for audiences 13 and above
>
> R — Intended for adult audiences above 17
>
> X — Even more mature than above
What would be a good way to add such feature? Ideally, on the post page, there is an area with radioboxes where the writer can make their selection. There must be a way to echo the choice in the post template.
Please provide code example if you choose to answer as my coding knowledge is limited. | Custom field will do the task. On the post page there's nothing to do great, just create a Custom Field called agerating or age-rating. Authors will enter the value of the field according to their content with G/PG/R/X.
Then at the frontend, edit single.php. Use this code inside the loop to retrieve the rating value:
<?php $age-rating = get_post_meta($post->ID, 'age-rating', true); ?>
Now use this code to show the rating:
Rated As: <?php echo $age-rating; ?>
Change the codes according to your needs. You can also style the Custom value box inside the Post panel after becoming experienced with this.
More Details: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "posts, php, rating, labels"
} |
Add $values to post_class()
This must be pretty simple, but it is eluding me. I need to add several classes to `post_class()` <
I can add one class in a page template, as below:
`post_class($even_odd);`
but I need to add several more, i.e. `$current_post` and `$current_in_total`
They won't `echo`, and they won't output this way: `post_class($current_post; $even_odd; $current_in_total;)`
I need to output these in a page template using `post_class()`, not add them via a hook in functions.php
Ideas? | Multiple post classes should be separated by a single space or should be in an array.
`post_class("$even_odd $current_post $current_in_total");`
Or
`post_class(array($even_odd, $current_post, $current_in_total));` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts, post class"
} |
Custom menu linking to page not found
I have built a series of pages and sub pages in wordpress.
Then, using custom menus with 5 x top level menus and then sub-menus under 3 of these top level menus:
Menu 1
Menu 2
- Sub Menu 1
- Sub Menu 2
Menu 3
Menu 4
- Sub Menu 1
- Sub Menu 2
- Sub Menu 3
- Sub Menu 4
Menu 5
- Sub Menu 1
- Sub Menu 2
Whenever I click on Menu 5 -> Sub Menu 1 OR Sub Menu 2 I get "Nothing Found for: Sub Menu 1"
I've just gone back into the page editor and clicked "View Page" and I get the same error. The pages I've created cannot be viewed. I can view all other Sub Menu Pages in all other menus except the last menu.
I thought the url might be too long but it is no longer than any other URL in any other sub menu?
ANy Ideas? | I figured it out.
The menu name was "Search" so wordpress redirected the subpages to the wordpress search results page and was assuming the search functionality. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, errors"
} |
How to use WP-FirePHP extension?
<
I'm simply supposed to call `fb('Error message','Lable')` but it doesn't work all the time. I can't figure out when and where the relevant files are being included and classes defined in order to make the call to the said method/function.
For example it doesn't work even when I call `fb()` from `wp-content\plugins\wp-firephp\FirePHPCore\fb.php` itself and open up ` (maybe because the file never gets included) but it works on ` Does that mean `wp-firephp` plugin only works for `/wp-admin` and related pages? Because I wanted to use its functionality on non-admin related pages like `/footer.php` and such. Am I doing it wrong? | I gave up on using the plugin and use FirePHP straight as a `mu-plugin`:
!FirePHP mu-plugin
And `firebug.php` file consists of:
<?php
/*
Plugin Name: FirePHP
Version: 0.1
*/
require_once( 'FirePHPCore/FirePHP.class.php' );
ob_start();
$firephp = FirePHP::getInstance( true );
function logit( $var, $title='From FirePHP:' )
{
global $firephp;
$firephp->log( $var, $title );
}
Then I call it from anywhere (theme, plugin, core) using the function:
`logit( $var_to_debug, 'The var contains:' );` | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "plugins, debug"
} |
How do I know if a user has a blog in Wordpress Multisite?
I have a Wordpress Multisite installation with Buddypress. I would want to restrict people from creating another blog so that they have only one blog.
How do I achieve this? | Check the user meta key `primary_blog`:
$user_has_blog = get_user_meta( $user_id, 'primary_blog', TRUE );
For users without a blog `$user_has_blog` will be false now. For other users `$user_has_blog` is the blog ID. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "multisite"
} |
Is there a way to delete images from the Media Library programatically?
I did a custom user profile page for wordpress that lets you update your profile including uploading your custom avatar and save that photo to the Media Library. Is there a way for the a specific avatar to be deleted using it's attachment ID? | Use wp_delete_attachment
<?php wp_delete_attachment( $attachment_id ); ?> | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "media library"
} |
Gravity Forms not loading under https, jQuery is not defined
I am using Gravity Forms on my Wordpress site, and so far so good. The problem is I have made the page secure (https/SSL), and this is making the form not to work.
It looks like the issue is how the site is trying to load jQuery. There are 23 JS errors on the page, which seem to be due to a failed jQuery load `"Uncaught ReferenceError: jQuery is not defined"`.
If I go to the page where the source is trying to pull the jQuery file, you'll see the error:`
Screenshot of the error:
 makes posts from existing content. For each post I have one picture - **how to make them featured programmatically**?
I do the:
$id = wp_insert_post( $my_post );
wp_set_object_terms( $id, $cat_ids, 'category' );
and I would like my next step to be inserting $image (file path or URI) as featured image. How?
Thanks in advance. | Try using **`set_post_thumbnail()`**.
Assuming you already know how to determine the `$post` (ID or object) for which to set the featured image, and the `$thumbnail_id` (ID) of the image that you want to set as the featured image:
set_post_thumbnail( $post, $thumbnail_id ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "posts, post thumbnails, automation"
} |
What table is the media's sort order stored?
I see that your can sort media by a numbered order in the media gallery for a post. But what table is this order stored in? I want to use this order to also order the images the same way in my posts. | This is the `menu_order`.
You can sort by multiple values too.
// Example
'orderby' => 'title menu_order' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "media, sort, table"
} |
How to display a category from a specific post-type
I have a custom post type called "my_people" along with a custom taxonomy named my_people_categories. It is used to display a list of people. I would like to show only the people in the list that are in a specific category in the custom taxonomy.
I have tried using the following short code, but it displays all the people and not just the ones in the categories named.
[catlist name=cat1,cat2 post_type=my_people orderby=title order=ASC]
Is there someway I am supposed to mention the taxonomy? Is what I am trying to do even possible using this addon? | according to the list of supported parameters you can possibly use it with a custom post type by setting `post_type` to `any`, but it doesn't appear to support custom taxonomies. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin list category post"
} |
advanced paging in wordpress
I can create pages in wordpress very simple like
www.mysite.com/profile
Now I have a question how can I make more pages in this page like `www.mysite.com/profile/edit` or maybe more pages like
www.mysite.com/profile/edit/image
Thanks in advance | In case, if you are asking about nesting of pages, then you do the following -
1. Create the edit page, and make the profile page the parent of the same (you can see this take effect when you update the page and the url changes to www.mysite.com/profile/edit)
2. Similarly, create the image page, and make the edit page the parent of the same | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, pagination"
} |
Integrating Magento and Wordpress Users
I've found posts on letting Wordpress manage Magento users and vise versa, but what I'm looking to do is not to have one manage users over the other. I'd like users to have the option to sign up through the shop or through the Wordpress main site, but enable Wordpress to use the Magento users and vise versa. Should I install both: < | While there are a lot of different solutions for integrating allowing use of Magento Blocks in Wordpress or using Wordpress functions in Magento, what you are looking for is _single login_.
It can be done via a WP Plugin:
1. **Mage Enabler.** It's a WP plugin that gives raw access to the Mage object - you can do single login plus access Magento methods within WordPress (pull templates from Magento, display categories, products and checkout from your blog).
2. **Magento WordPress Integration**. I haven't examined this one.
Or via a Magento extension:
1. **FIshPig's WordPress Customer Synchronisation**
2. **Single Sign-On For Magento And WordPress** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "magento"
} |
Add forward slash on categories url (serve one version of a url)
How can I a add forward slash on categories URLs and serve only that version of a category (meaning URLs not ending in forward-slash will redirect to URLs ending in forward slash).
I manage to remove the category base using the "WP No Category Base" plugin but I need to add a forward slash on the category URL.
Examples:
www.example.com/es <- this is a category (needs a forward-slash '/')
www.example.com/es/hola.html <- this is a post so, it's ok, no changes needed.
The plugin Permalink Trailing Slash Fixer doesn't solve the problem here. | Filter `category_link` so WordPress **creates** slashed URLs for categories, and `redirect_canonical` so it **accepts** those URLs:
add_filter( 'category_link', 'wpse_71666_trailingslash_cat_url' );
add_filter( 'redirect_canonical', 'wpse_71666_trailingslash_cat_url', 20, 2 );
function wpse_71666_trailingslash_cat_url( $url, $request = '' )
{
if ( 'category_link' === current_filter() )
return rtrim( $url, '/' ) . '/';
if ( "$url/" === $request and is_category() )
return $request;
return $url;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "categories, url rewriting, redirect, urls, plugins url"
} |
List products from current category
This code is from the archive page and list all products with a certain tag, can someone please help me to modify this code to make listing products only from current category:
<?php if ( is_product_tag() ) :?>
<?php do_action('woocommerce_before_shop_loop'); ?>
<ul class="products">
<?php while ( have_posts() ) : the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product'); ?>
<?php endwhile; // end of the loop. ?>
</ul>
<?php do_action('woocommerce_after_shop_loop'); ?>
<?php endif; ?> | Your best bet to do this would be to add a filter/hook on the specific tag. See this snippet at the WooCommerce API docs site on excluding a category for the proper format and to get going in the right direction. <
But if you want a down and dirty way to filter for a specific tag on this content part then you can wrap an _if then_ around your woocommerce_get_template_part().
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( *** product has tag *** ) { ?>
<?php woocommerce_get_template_part( 'content', 'product'); ?>
<?php endif; ?>
<?php endwhile; // end of the loop. ?>
You can look at the API docs on the product tags at <
Make sure you're following WooCommerce theme customization recommendations at <
Unless you want this to be global you'll have to account for the various outputs and determine when you don't want to filter both products and tags. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, tags, list, plugins"
} |
Custom Post Type with image gallery
I'm doing research on custom post types for a Wordpress site I'm going to be putting together for a client of mine. The basics of the Custom Post Type seem pretty straight forward. What I'm trying to determine is the best way that I could have an image gallery as part of my custom post type.
For example, a custom post type would be a car. In addition to the details of the car (make, model, year, mileage, etc.) there will be 1-n images associated with it that should be part of the post (modified inside the post, removed along with the post, etc.) Ideally I'd want thumbnail images that open up to a lightbox of some sort.
Hopefully this is something that can be accomplished without totally hacking up Wordpress. | Custom Post Types can have image attachments like other post types. A simple way to display them is via the gallery shortcode. There are several plugins out there to enhance the gallery output, or you can also display attachments in a single post yourself via the API, for example with `get_posts`.
The only requirement you won't get out of the box is deletion of attachments when the parent post is deleted, as images can be used in other posts so that could potentially break things. If that's not a concern, you can delete attachments on post delete with a bit of code hooked to deletion:
function delete_post_children($post_id) {
global $wpdb;
$ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_parent = $post_id AND post_type = 'attachment'");
foreach ( $ids as $id )
wp_delete_attachment($id);
}
add_action('delete_post', 'delete_post_children');
taken from < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, images, gallery"
} |
Programatically re-order images in the ACF gallery add-on. Orderby Title, ID, etc
I have a gallery field using the advanced custom fields gallery addon.
This is how I am outputting my gallery fields/images in my theme...
<?php
$images = get_field('gallery');
if( $images ): ?>
<div id="gallery-1">
<?php foreach( $images as $image ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endforeach; ?>
</div>
<?php endif; ?>
And this is the only way in the documentation I can see how to implement it.
Does anyone now who how I can order the images by title, id or anything when they are outputted in the loop?
Many Thanks | You can use Php's `usort()` function with a callback. For example, if you want to sort images by ID, you could try something like this (stealing the filter that @Milo used in their answer):
<?php
function sort_callback($a,$b)
{
if ($a['id'] == $b['id']) {
return 0;
}
return ($a['id'] < $b['id']) ? -1 : 1;
}
function my_acf_load_field( $field ){
usort( $field, 'sort_callback');
return $field;
}
add_filter( 'acf_load_field-gallery', 'my_acf_load_field' );
You can adjust the `sort_callback` function to sort by whichever value in the $image array that you'd like. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "advanced custom fields"
} |
post_content with Contact Form 7
Is it possible to add name="post_content" to more than one input field?
I am using Contact Form 7 plugin, and now only the last input field with name="post_content" is gathered in the post.
If I put the whole form in a div I only get raw data (not the filled one). Can someone help please. | If 2 fields have same name, web browsers ignore one of them. So you can't have the name as `name="post_content"` using contact form 7(or anything else)
You can however make the name as `name="post_content[]"` which tells the browser that the field is not single & the browser won't ignore any of them. If you use this technique, you can't use this(as far as i know) with the contact form 7 plugin. You'll need to either create the form yourself or use a plugin that supports this. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin contact form 7"
} |
What is the best method to close off the backend?
**The goal** : Completely remove the ability to access the WordPress backend on the production domain. Ex. return a 404 for <
**Purpose** : I don't want any possibility of WordPress' backend being accessed across the Internet. Instead, it will only be accessibly via VPN on an internal domain (i.e. < _This ensures that no one could ever brute force attack the login page._
I could restrict logins to a given IP address, but I don't want to keep up with a list of IPs. I'd prefer to use the security my VPN already offers.
Consider that `wp-admin` still has to be accessible in some fashion because there could be resources that the frontend calls.
Are there any solutions beyond redirecting `wp-login.php` somewhere else? | If you know the sub-net of your VPN you could restrict access to /wp-admin via .htaccess using standard Apache rules.
<Directory /var/www/wp-admin/>
Order deny,allow
Allow from 192.168.1.0/24
Allow from 127
</Directory>
Obviously you'd need to adjust the directory and IP address subnet to suit your needs.
To restrict access to a specific file:
<Files _FILE_.php>
Order allow,deny
Deny from all
Allow from 127.0.0.1
</Files>
Again you can use a sub-net mask to suit your VPN. | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 5,
"tags": "wp admin, security"
} |
Individual rss feed entry length for categories?
I know how to retrieve the rss2 feed from a category in wp, namely adding `/feed` behind the category name. However when I do this, not all entries from that feed are included in the rss, this is because I set the feed restriction to be 50 at the admin backend.
I would like to know if a feed length could be set indiviually for each category/feed programatically.
I could not find any api settings for the size of the feeds ... any help is welcome here.
Thanks for your help. | You _should_ be able to use `pre_get_posts` and set the `posts_per_page` to 50 conditionally (on being feed for categories). Unfortunately there is this unresolved trac ticket.
The only work-around is to do hook into `post_limits` and replace the `LIMIT` part of the SQL query directly.
add_action('post_limits','wpse71759_category_rss_limit',10,2);
function wpse71759_category_rss_limit($limit, $query){
if( $query->is_feed() && $query->is_category() ){
$paged = $query->get('paged') ? (int) $query->get('paged') : 1;
$per_page = 50;
$page_start = ($paged-1)*$per_page;
return "LIMIT $page_start, $per_page";
}
return $limit;
} | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 9,
"tags": "categories, rss, feed"
} |
WordPress templating system for custom plugins
I'm creating a custom plugin which needs to display HTML with dynamically updated values.
To illustrate, here's what I want to achieve:
<h1><?php print $title; ?></h1>
<h3><?php print $subtitle; ?></h3>
<div class="description"><?php print $content; ?></div>
How can I define a template, pass some variables and get output in return from my custom plugin? I do not want to embed everything as a variable name as it's messy; going back between PHP and HTML in a middle of a function doesn't seem any cleaner either.
What is WP way of doing this?
Thanks! | The various styles of mixing and matching HTML and PHP has always been a bear. Circumstances sometimes dictate the method you use, but many developers prefer one style or another and WordPress tends to use the style in your example.
Another option, which is a bit cleaner in my opinion is to make use of the heredoc syntax in PHP which allows for simple variable substitution. <
$Output = <<< EOF
<h1>$title</h1>
<h3>$subtitle</h3>
<div class="description">$content</div>
EOF;
return $Output;
You can't do away with the PHP variables entirely, but you can make it easier to write, read, and maintain. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
How to resolve 404 errors for wordpress comments/feed when I have disabled comments
I have disabled comments in my wordpress site. So comments/feed url is giving 404 error. So how should I resolve these errors? doaminname/feed works fine. But domainname/comments/feed is giving error. So I want to fix that error. | I added `remove_action( 'wp_head', 'feed_links', 2 );` in functions.php file. and
added in the header.php.
This fulfilled my purpose. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, 404 error, feed"
} |
Check if on last page of paginated post using wp_link_pages
A client of mine reviews products on his site, and wants to display the review criteria and score on the last page of each posts. Typically, there are 3-5 pages per post, and I'm looking for a way to check if we're on the last page.
‹!--nextpage--› is used in the post to divide it into pages, and wp_link_pages on the front-end to display pagination links.
I've been able to find ways of checking if we're on page one, or not on page one, or on a specific page. But nothing for checking if we're on the very last page. | You can find this info in the global vars `$multipage`, `$numpages`, and `$page`
global $multipage, $numpages, $page;
if( $multipage && $page == $numpages )
echo 'last page'; | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "pagination, wp link pages"
} |
Editing Loop So It Targets Specific Tags?
Confused on how to achieve this, but what I'm trying to do is load posts with the tag "reviews" in the loop on the homepage.
Index.php:
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
get_template_part( 'content-reviews', get_post_format() );
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'no-results', 'index' ); ?>
<?php endif; ?> | Use the `pre_get_posts` action to modify the main query. Place this in your `functions.php` file:
function wpa71787_home_tag_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'tag', 'reviews' );
}
}
add_action( 'pre_get_posts', 'wpa71787_home_tag_query' );
You can set any valid parameters of `WP_Query` with this method.
Edit, secondary query excluding tagged posts, use tag ID:
$query = new WP_Query( array( 'tag__not_in' => array( 42 ) ) );
while( $query->have_posts() ):
$query->the_post();
// loop stuff
endwhile; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, loop, tags"
} |
Receiving error with Custom Tables plugin
How to resolve this warning which is shown when I use the Custom Tables plugin? Can anybody help me please
> Warning: Invalid argument supplied for foreach() in ..\wp-content\plugins\custom-tables\pages\show_table.php on line 378 | A quick and dirty "fix" would be to change line 378 in that file and cast the `$qry` variable to an array. It should make the error go away, however, to fix the actual cause of the problem some refactoring may need to be done. You could drop the plugin author a note.
foreach ($qry as $row) {
// becomes:
foreach ((array) $qry as $row) { | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, errors"
} |
How to check if the current page is a "personal activity"-page in buddypress?
I want to modify some general text in my personal-activity page in buddypress. Does any one know any conditional tag like `is_page('activity')` things are there for checking this? the page can be navigated as
> member profile page -> activity tab
Thanks in advance :) Vignesh | I found the conditionals in docs :) they are like as follow,
bp_is_user_profile() /* will check the current page as personal profile */
bp_is_user_activity() /* will check the current page as personal activity */ | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "buddypress, conditional tags"
} |
Wordpress Image Attachment using remote image
Is it possible to use remote image as wordpress attachment? * Not stored on our server..
How about the code/script? i see that attachment is act as post in database.. seems it's possible.
_**UPDATE_**
what i need is to programatically attach image from remote URL and the final goal is the remote image can show as attachment page template just like uploaded image. is that possible?
Any suggestion would be highly appreciated.
Thanks. | You'll want to get very familiar with wp_insert_attachment(), download_url() and media_handle_sideload(). It's a bit lengthy to get into the details here, but it absolutely can be done. I used these methods to create a media tab that allows a user to put in a vimeo/youtube URL which I store in a postmeta and use their (vimeo/youtube) automatic thumbnail endpoints to attach an image to the post representing the video. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, attachments"
} |
Sub-category single post styling?
*CLARIFICATION: I'm trying to style the single post view of some categories & sub categories. The suggested solution works, but only on a page of posts from the selected categories.
Eg. If a post has a category 0f 59 (or is a child category of 59) then load a stylesheet.
Here's what I've tried from the Codex-
<?php
// if the category is 59 or a 59 SUBcategory
if (cat_is_ancestor_of(59, $cat) or in_category(59)): ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/products.css" type="text/css" media="screen" /><?php endif; ?>
Any ideas why it's not working? Thanks | Try this `if` statement instead:
if ( is_category() && ( is_category( 59 ) || cat_is_ancestor_of( 59, get_queried_object_id() ) ) )
**Update** : To work for single posts:
if ( is_single() && $terms = get_the_category( get_queried_object_id() ) ) {
foreach ( $terms as $term ) {
if ( $term->term_id == 59 || cat_is_ancestor_of( 59, $term->term_id ) ) : ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/products.css" type="text/css" media="screen" />
<?php
break;
endif;
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "conditional tags"
} |
Trying to reorder posts by custom field
I'm running WooCommerce and am trying to get the default product display to be sorted by the sku field in ascending order. So far I've come up with this:
/* Order products by SKU */
function reorder_products_by_sku( $query ) {
if(is_shop() && ! is_admin() && $query->is_main_query()) {
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', 'sku');
$query->set('order', 'ASC');
}
}
add_action( 'pre_get_posts', 'reorder_products_by_sku' );
This just tells me there are no products found which match my selection. Can anyone point me towards what I'm doing wrong?
Thanks | You might want to take a look at the WooCommerce docs, there's a good snippet there showing now to add custom sort orders.
The link is <
Once you've 'defined' your custom order you'll of course need to set it as the default in the store settings. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, query, plugins"
} |
Bought custom navigation menu from codecanyon, how to change feature.php?
I bought a nav-menu with css but not sure how to use this in my wordpress theme. Is there a standard way to implement it?
Like this question:
Documentation that came with the navmenu: is this: < | For what I understand you want to implement a custom menu in your wordpress theme.
First of all you have to understand the template structure of the theme you're using. Most themes have the navigation menu in the header.php or templates/head.php, it depends.
Additionally, will you use a static menu or dynamic? Dynamic meaning you're adding the pages (created via wordpress dashboard) automatically in the navigation menu structure. Static is just a copy paste operation of the nav-menu.
Lastly, the author of the nav-menu you've purchased is using wordpress as well. It may be worth asking him for advice.
Hope it helps you moving forward. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, css"
} |
Pending status by default for a specific role
I would like to prevent users from one specific role from publishing directly their articles. Only administrators should be able to approve these. The only choice they would ever have is to put their articles as pending or draft. Any other roles may publish if they want. Is there a way to do so without any plugin and without having to dig too deep into the code?
Thank you | The following code can go in the `functions.php` file of your theme. However, this kind of operation should not really be bound to a theme. Changing themes would allow the users with your specific role to publish again. Therefore, just put the code in simple plugin.
<?php
/**
* Plugin Name: My specific roles and capabilities
* Plugin URI:
*/
$role = get_role('specific-role'); // Pick your role
if ( ! empty($role))
{
$role->remove_cap('publish_posts');
}
See codex: `get_role()` and `publish_posts`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "user roles, capabilities, post status"
} |
Where to store the name of a custom table?
I'm extending the `$wpdb` object with properties for my custom tables.
function setup_wpdb()
{
global $wpdb;
// Create properties for custom tables
$wpdb->my_plugin_table1 = $wpdb->prefix.'my_plugin_table1';
$wpdb->my_plugin_table2 = $wpdb->prefix.'my_plugin_table2';
}
Is this a good practice? I guess as long as the properties are prefixed with the plugin name, it should be fine. Defining a constant may work too. What do you prefer and why? Thanks. | As long as...
1. You use `$wpdb->prefix` (or `$wpdb->base_prefix`) to prefix the table
2. Your table name is someplace public, and easily available for other plugins, themes and end users to use and extend
I would say either setting the table as a property on `$wpdb` or using a constant is fine. If you choose to use `$wpdb` be aware that another plugin (or theme or whatever) can just overwrite your property in the same way you set it. For that reason, it's a bit more "safe" to use something like a constant.
Also, always carefully question whether or not you need to add a table.
I tend to use constants, but if I'm doing something like creating a `termmeta` table, then I would use a `$wpdb` property. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, wpdb, customization"
} |
Is it possible to add new user Roles?
I wonder if it is possible to create a new user role and give him special limited abilities?
I'd like to have some users who can only add events onto the calendar. They should only be able to work within events calendar taxonomy and edit add their posts but not publish them something like contributor but more limited! | Yes. WordPress has robust built-in Roles and Capabilities system desgined to do exactly what you are looking for.
To add a new role, use the `add_role()` function in your theme's `functions.php` or a plug-in like so:
$role = add_role( 'event_manager', 'Event Manager', array(
'read' => true, // True allows that capability
) );
if ( null !== $role ) {
echo 'Yay! New role created!';
} else {
echo 'Oh... the event_manager role already exists.';
}
To add a new capability, use the `add_cap()` function like this:
$role = get_role( 'event_manager' );
$role->add_cap( 'manage_events' ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 6,
"tags": "user roles"
} |
Stop WP from creating "Sample Page" and "Hello World!" post
Is it possible to stop WP from creating the "Sample Page" and "Hello World!" post when creating a new blog? | **_If you're using Multisite_**
The accepted answer is destructive in that it cancels all other set-up items in the overridden function. A less destructive way to do it _for multisite installs_ is to delete the default content during new blog creation by hooking in to `wpmu_new_blog`
add_action( 'wpmu_new_blog', 'delete_wordpress_defaults', 100, 1 );
function delete_wordpress_defaults(){
// 'Hello World!' post
wp_delete_post( 1, true );
// 'Sample page' page
wp_delete_post( 2, true );
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 11,
"tags": "posts, pages"
} |
Moving a wordpress.org website to another domain name?
I currently have a wordpress.org website on a server with a specific domain name. I would like to move it all to a server with another domain name as I have changed my company name.
What is the best way of doing this without losing the links (Both internal links and external links going towards the site)? Many thanks in advance | Here is my solution.
First download this file.
Then follow these steps.
In shortly
1. Backup/download your database.
2. Upload it to your new site.
3. Copy all wordpress folder including wp-admin,wp-content etc from your old site to new one.
4. Edit the downloaded php file, change the password. you need to change the password in this line. define('DDWPDC_PASSWORD', 'Replace-This-Password');
5. Now place the downloaded php file in the root directory of your NEW site.
6. <
7. Enter the password you entered in step 4.
8. Now you can see a form filled with your old db values. Just change the details. Thats it. You are done.
PS: I have included the screenshot of how value appears in the form
!enter image description here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "links, hosting, domain, dns"
} |
WooCommerce Grid / List view
Is there any experience with Woocommerce Grid / List view plugin, I set to automatically start the list view but the problem is that while the page is loading initially opens a grid view and instantly change to list view, it takes 1 second but it seems confusing.Is there any idea how it could be resolved?
I took the code from the following link
jQuery(document).ready(function(){
jQuery('ul.products').addClass('list');
}); | Undo any changes you've have made to the file, then add this **at the top** :
if ( jQuery.cookie( "gridcookie" ) != "grid" ) {
jQuery.cookie( "gridcookie", "list", { path: "/" } );
}
**Update:** Sounds like a FOUC. Let's take a different approach - remove the code you added above & try adding the following to your theme's `functions.php`:
add_action( 'woocommerce_after_shop_loop', 'wpse_71885_shop_loop_list_init' );
function wpse_71885_shop_loop_list_init() {
?>
<script type="text/javascript">
jQuery( "ul.products" ).addClass( jQuery.cookie( "gridcookie" ) || "list" );
</script>
<?php
}
This will add the grid/list class to the product list _immediately_ after it enters the document (as opposed to waiting for document ready). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "list, plugins, views"
} |
Can't access dashboard, connection times out (other pages work fine)
I have a multisite Wordpress installation with 2 blogs, on different domains. One of them works fine, but I just realized that for the other, I can't access the admin area. I can log in, but when accessing /wp-admin the request never returns and eventually times out. It was working fine the last time I tried (a few weeks ago), and I didn't make any changes since then...
What could be causing this? How can I get more info to help diagnose the problem? I can't find any logs on the server...
EDIT: I was using Firefox when I saw this problem; I just tried again in Chrome, which seems to have a longer timeout, and the dashboard finally appeared. The other admin pages seem to work fine, but the dashboard takes a very, _very_ long time to load.
BTW, I'm running Wordpress 3.3.2 on IIS. | OK, I just found the problem: I had more than 5000 spam comments (most of them from an IP range I had blacklisted). Apparently it's a problem for the dashboard, although the comments page works fine... I deleted those comments directly in the DB, and everything is back to normal. Now I just need to find a way to completely block the source IPs in IIS, otherwise I'll have the same problem in a few weeks... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "wp admin, dashboard"
} |
Can I connect a page to a taxonomy?
I'm creating a website for a soccer club. It has news, reports and media custom post types. There you can connect the post to the Team taxonomy. But I also need to have a page for that team where I can add info, team photo etc.
Can I connect a page to a certain taxonomy? For example I got a page called "Team 1" and connect that to the taxonomy term "Team 1"?
If not what is the best option? | You can register taxonomies for objects (such as posts & pages) like so:
add_action( 'init', 'wpse_71914_assign_page_taxonomy' );
function wpse_71914_assign_page_taxonomy() {
register_taxonomy_for_object_type( 'taxonomy_name', 'page' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, taxonomy"
} |
How to prevent automatic redirection of 404 errors and "incorrect" URLs?
Wordpress has a feature whereby it will automatically redirect your URLs if it percieves them to be written wrongly. Here is an example: I have a page called `my-page`
If I go to:
www.mysite.com/something/my-page/
it will immediately redirect me to
www.mysite.com/my-page/
as nothing exists at the first URL.
How can I turn this feature off, and instead just get a 404 if incorrect URL's are typed in? | This worked for me:
remove_action('template_redirect', 'redirect_canonical'); | stackexchange-wordpress | {
"answer_score": 33,
"question_score": 21,
"tags": "redirect, urls, 404 error, rel canonical"
} |
Long running action from plugin
I'm creating a WordPress plugin that will copy posts data to a remote database, I know it will take a while to transfer all the posts.
How should I create copy functionality so it won't timeout? Ideally it would run in background and show some notification on completion. | You could use WordPress' pseudo-cron and `wp_schedule_single_event`.
<?php
// add the action.
add_action('wpse71941_cron', 'wpse71941_long_running');
function wpse71941_long_running($args)
{
// might need to call `set_time_limit` here
set_time_limit(0);
// do long running stuff here
// return normal time limit
if($l = ini_get('max_execution_time'))
set_time_limit($l);
}
// schedule the event for right now
wp_schedule_single_event(
time(),
'wpse71941_cron',
array('args' => 'for', 'callback' => 'function')
);
Not sure if you need to mess with time limit. WP does call `ignore_user_abort` at the top of the cron script. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "plugins, wp cron"
} |
WooCommerce Layered Nav Widget
Has anyone used the "WooCommerce Layered Nav" widget. I wonder if the attributes could be visible on the single product page? | Finally i solve this problem:
<?php if (is_singular() ) : ?>
<?php foreach ($attributes as $attribute) : ?>
<h3><?php echo $woocommerce->attribute_label( $attribute['name'] ); ?></h3>
<ul>
<li><?php $values = woocommerce_get_product_terms( $product->id, $attribute['name'], 'names' );
echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values ); ?></li>
</ul>
<?php endforeach; ?>
<?php endif ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, navigation, page attributes"
} |
Show or hide a widget from pages
I want to add a check option to the wordpress admin sidebar when I am writing a post or a page to display a specific widget. I tried display-widgets plugin but I want to be able to show a widget directly while writing the post.
Or is there is another way to do this it will be OK. | Barring the discovery of a plugin that does this already (I'm not aware of any that specifically do what you want) you'll need to create your own. `add_meta_box` and `add_filter('widget_display_callback', $instance, $widget, $args)` should be the bulk of what you need | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets"
} |
How to use WordPress HTTP API to download file from remote location
So this PHP code works for me:
$ch = curl_init( TCS_CPDF_REMOTE_ZIP );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$data = curl_exec( $ch );
curl_close( $ch );
file_put_contents( TCS_CPDF_LOCAL_ZIP, $data );
but when trying to use the WordPress HTTP API:
$the_body = wp_remote_retrieve_body( wp_remote_get( TCS_CPDF_REMOTE_ZIP ) );
file_put_contents( TCS_CPDF_LOCAL_ZIP, $the_body );
I end up getting a 0KB file, so the above WordPress version is not working.
So how do you download a file from a remote location using the WordPress API? | Check out `download_url()` \- it's only loaded in the admin, so you'll have to include it (or write your own) if needed on the front-end.
From `download_url()` you can use:
$response = wp_remote_get(
TCS_CPDF_REMOTE_ZIP,
array(
'timeout' => 300,
'stream' => true,
'filename' => TCS_CPDF_LOCAL_ZIP
)
); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "http api, wp filesystem"
} |
Updating post content on the front end
I have used the code below to add frontend editing to my posts/pages. How would I go about saving the post content when an update/save button is pressed?
$post_id = get_the_ID();
$settings = array(
'wpautop' => true,
'media_buttons' => true,
'wpautop' => true,
'tinymce' => true,
'quicktags' => true,
'textarea_rows' => 18
);
$post = get_post($post_id, 'OBJECT');
wp_editor($post->post_content, 'epicpagecontent', $settings );
<input type="submit" name="submit" id="submit" value="Update"> | You should use the `wp_update_post` function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp editor, post content"
} |
What's the best way to manage a lot of 301 redirects in WordPress?
Currently my site has a lot of 301 redirects we are managing in our .htaccess file (several hundreds 301 redirects); however, I am wondering would it be better and more optimal I use a plugin such as Redirection to accomplish this? | This is not really a clear question, and plugin suggestions are usually closed, as per the FAQ <
It all depends on what kind of work you want to do: either edit .htaccess or work with a plugin GUI.
Redirection works well and will allow entry of rules via CSV file and logging of all redirects as well as 404's.
With Redirection, you sacrifice a amount of site performance, but it may be worth it to you. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "htaccess, redirect"
} |
get_pages() as per custom menu order
I'm working on Single Page WordPress Theme where I want to get_pages() as per custom menu order.
I have gone through the reference for get_pages() which only allows for default menu :
get_pages('sort_order=asc&sort_column=menu_order');
Is there any way to get_pages() as per **custom menu order** ? | I Have Found My Own Solution. I Tried To Get Page ID Of Each Custom Menu Item & Rendered Page Based On That ID.
Reference : wp get nav menu items
Like This...
$menu_name = 'primary-menu';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
foreach ( (array) $menu_items as $key => $menu_item ) {
$qcPageID = $menu_item->object_id;
$qcPageData = get_page( $qcPageID );
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pages, menu order"
} |
Layer post title on top of image Wordpress featured thumbnail image
I'm currently trying to layer a post title on top of the posts featured image but all I see at the moment is " **);">** " instead of the image.
The code I'm using is as follows:
<div style="width:609px;height:364px;background-image:url(<?php the_post_thumbnail(); ?>);"><h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2></div>
And here is the CSS for the H2 style
article h2 a{
background-color:#bf0c08;
color:#fff;
width:auto;
font-size:30px;
text-decoration:none;
padding:8px;
max-width:479px;
line-height:60px;}
Any idea where I'm going wrong? Also a solution would be awesome :)
You can see this on www.ridermagazine.co.uk | `the_post_thumbnail()` does not return the path of your image. Instead, it returns the complete HTML markup for that image.
You can use this instead:
`$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) ); echo $image[0];`
If you want a specific size you can pass an additional parameter:
`$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); echo $image[0];`
You can either use a keyword for the size (`thumbnail`, `medium`, `large` or `full`), a size you defined with `add_image_size`, or pass an array with your desired size like so: `array( 100, 200 )` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "css, post thumbnails, html5"
} |
Wordpress Custom Menu Widget Style
I am wondering if anyone knows the best method for splitting 1 custom menu widget (located in my sites footer) in to 2 columns. There are a total of 8 links, so I would like it to be split in to 2 columns of 4 links. Not sure if there is a function for this or is there some CSS to achieve this? The HTML markup from the widget looks like:
<ul>
<li id="menu-item-133" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-6 current_page_item menu-item-133">
<a href="#">Link</a>
</li>
</ul>
repeat that structure 7 more times for the line items code. | Purely with CSS you could set a width for menu items, float them and then set the UL to twice that:
footer ul {
width: 200px;
}
footer .menu-item {
float: left;
width: 100px
}
(I don't know what elements you are using to designate your footer, you'll need to update that to match your structure.) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "menus, widgets, columns"
} |
Replacing the WP.me URL shortener with Bit.ly
I am setting up a big blog for a client and we're looking to replace the wp.me shortlinks in the header and in everything with our custom domain on bit.ly.
I have working code to build the Shortlinks, im just wondering if there is any way to replace the functions so pressing "Get Shortlink" and tweeting links, would use our bit.ly
Is there a way to add action and replace the existing wp_get_shortlink and a like? To be clear, i want all the same functionality, just with a different short link. | Totally possible, here is a great walkthough: <
Bullet points:
-Write a function that gets the bitly link upon publish
-Remove the default action and add your own
-Call wp_get_shortlink() like normal and bitly will be used | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortlink"
} |
Why is the media upload button not in the main toolbar & can it be placed there instead?
Is there a good reason why the wp media upload button is not placed within the main edit toolbar, and can we put it there instead of floating above?? | There is an action `'media_buttons'` where these buttons are inserted. Some plugins are using that action to add more buttons, dropdown lists or links. If they had to use the TinyMCE toolbar, they had less room and more restrictions regarding style and JavaScript access.
In short: the current placement is better for plugins.
Moving the default button to the toolbar would probably break some core scripts that depend on that position in the DOM. Maybe you can move it around after `onload`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "tinymce, editor"
} |
Extract a link in the_content()
I'm trying to improve a bookmarks manager/theme I've built (<
Right now, each post is simply a link:
`<a href=" Tumblr</a>.` ie: that one single link is the entire content of `the_content()`.
Easy enough and works great. Next, I want to be able to get a screenshot of the site via WordPress.com's mShots.
Problem is, I can't seem to extract that link from `the_content()` and feed it into the `<img src="">`.
If that wasn't clear, here's what I'm trying to do:
<img src=" />
I've tried severalvariations on this:
$content = get_the_content();
$link = preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $content, $match);
But I can't achieve the basic task of extracting that link from `the_content()`. At the moment, I simply get a formatted link output. I can't find a way to grab the url instead of grabbing the whole link.
Thanks for any suggestions. | You're just looking in the wrong place:
php > $txt = '<a href=" Tumblr</a>';
php > $matches = array();
php > echo preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $txt, $matches);
1
php > print_r($matches);
Array
(
[0] => Array
(
[0] =>
)
[1] => Array
(
[0] => 4
)
) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "the content"
} |
Get a path to a different plugin
To get a the path to a plugin you can use `plugin_dir_path(__FILE__)` \- but this obviously has to be called from within the plug-in.
How can you _reliably_ get the path to plugin B (`pluginb/pluginb.php`) from within plug-in A?
**Edit:** Its assumed you know the slug of the plug-in you're after (actually you can get them from `get_plugins()`). But I would like it to work generally. | My best guess would be:
if ( ! is_file( $dir = WPMU_PLUGIN_DIR . '/pluginb/pluginb.php' ) ) {
if ( ! is_file( $dir = WP_PLUGIN_DIR . '/pluginb/pluginb.php' ) )
$dir = null;
}
return $dir;
However, the danger here is still the assumption of the plugin's "basename" - a well written plugin will still function even when its directory and/or main file has been renamed (for whatever reason).
Which goes back to my original comment - depending on _which_ third-party plugin this is referring to, many authors define their own methods/constants to hold the plugin path - it would make sense to check for their existence & use these instead (if available). | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 13,
"tags": "plugin development, directory"
} |
The_excerpt() doesn't parse <!--more--> - how to change that?
I'm using `the_excerpt();` in blog.php file (post listing page) and it doesn't recognize `<!--more-->` if "Excerpt" field is empty and it grabs the beginning of the content as excerpt.
This issue is described here: < but I don't know why did WordPress disable `<!--more-->` for the excerpt (if excerpt field is empty and content is used as excerpt)?
Can i enable that back? | I do not know why the WordPress powers that be decided to do it the way they did but they don't consider the part before the `<--more-->` to be the same as the excerpt. Whether that makes sense or not is probably an irresolvable matter of perspective. I'd accept it and make do. The distinction actually adds flexibility to your content management so long as you are aware of what is happening. If you want to use the `<--more-->` just do this...
if ( !empty( $post->post_excerpt ) ) the_excerpt();
else the_content();
The code that parses the `<--more-->` is hard-coded into `get_the_content` so it isn't just a matter of removing/adding a filter, though certainly you could juggle filters, or create one, to make this work. That is a more complicated solution and is in my opinion not worth it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, functions, loop, content, excerpt"
} |
Basics of changing plugin output
There's a Mailchimp plugin I would like to alter it's output in order to match my needs. For example:
1. Order in which fields are loaded are not correct
2. Positioning of the plugin's response messages is not correct.
I have already tried modifying everything using only CSS but I really need to modify the HTML of this plugin.
Is there a way to do this without hacking the plugin itself?
Thanks a lot! | Take a look at WordPress hooks from the Plugin API. There are actions and filters to be used by plugin authors so that other developers could alter the content without changing the core code. However, if they are not used properly (or missing), the only two options are CSS changes (wherever possible, because stylesheets could override the UI at some cases) and the WordPress API hooks (so that you could manage the content globally from WordPress and rearrange order from calling different functions). Custom requirements usually expect flexible plugins with hooks and therefore the lack of them doesn't give you any other clean options. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, functions, css"
} |
WP-Syntax plugin not working
I am new to wordpress (installed yesterday for first time). In order to add syntax highlighting i installed the WP-Syntax plugin and i copied pasted the following snippet in the edit post window. Its copied from the usage examples.
<pre lang="php">
<div id="foo">
<?php
function foo() {
echo "Hello World!\\n";
}
?>
</div>
</pre>
However when i preview it on the main site i end up seeing the following as it is, whereas i was expecting to see highlighted php code. Could anyone point out what could be the issue? | Have you looked to see if the correct style sheet is being loaded to change the highlighting? It appears to be a white background with some font styling for the different language. If you want something more than that, you will need to customize the css for it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "syntax highlighting"
} |
How can I reduce the amount of files loaded/included per plugin?
I have a Wordpress site that uses several plugins, namely 8. Most of these plugins include a lot of their own JS and CSS files, some even include so much as 3 separate CSS files. One can imagine that this does a number on the amount of HTTP requests and thus the load time.
Many of these plugins also only get used on certain pages, yet the JS or CSS is still loaded on pages where they are not used.
All of theses files are included automatically in the through WP_head();. Is there a way I can manually include these files and then load them conditionally? Preferably without having to adjust the plugin code itself?
Are there other common practices regarding the many files included by a bigger number of plugins? | Previous versions of WordPress didn't really provide a good means to conditionally enqueue stylesheets and JavaScript within a plugin (i.e. only when needed). So most plugin authors enqueued both on every WordPress init/load, even if the plugin wasn't being used on a given page.
Current versions of WordPress allow for enqueuing later in the flow so you you can, for example, enqueue on your shortcode init/parse.
So you really have only a few options here:
* Use Minify to reduce the file size and in some cases combine files to reduce the number of requests, file I/O, and bandwidth. (Already suggested by @m4t1t0)
* Directly modify the plugins to prevent the enqueue if the plugin is not actually used on a given page.
* Open a support ticket for the appropriate plugin and request the author to update the plugin.
Hopefully other users here might have some suggestions for you. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "plugins, javascript, css, wp head, performance"
} |
Conditional for a Single Post That Belongs to a Category?
I have categories like `gaming` and `movies` on my website and when a user visits any of these categories the content in the sidebar is displayed depending on the category they are in. So gaming content for the gaming category, movie related content for movies.
When a user selects a post in either of these categories, I have it defaulting to the sidebar that displays on the home page since I don't know how to keep the sidebar displaying the same content that is on the category pages.
The closest I could get would be something like `<?php if ( is_single() ) : ?>`. How would I add `is_category( 'gaming' )` so it can target a `single page` (single.php) that belongs to the category `gaming?` | You can combine conditions:
if ( ! empty ( $GLOBALS['post'] )
&& is_single()
&& in_category( 'gaming', $GLOBALS['post'] )
)
{
// do something
}
See PHP manual: Logical Operators and Exclude custom function content from certain pages. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "custom post types, posts, loop, conditional tags, conditional content"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.