INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Not sure how I would go about doing this in WP.. related to custom tags
Okay, so I want to do something, and after searching on Google I couldn't find any answers. Maybe you guys can help.
basically, I want to assign every post with a little bit of unique identification information. Every post would be tagged white, gray, or black. **I don't want to use categories or tags because I want to display this "unique identifier" on the home page only, and not in the posts where the categories and tags are already shown.**
For example, If I made a post about white tigers, I would want to **identify it as white post** (no racism or anything intended, just an example), and display it on the home page only.
If I made a post about gray tigers, I would want to identify the post as gray, and you get the point.
_**How can I go about doing this without a plugin?_**
**TL;DR - Want to identify each post with a unique identifier, but can't use categories and tags.**
Please help! | There are two mechanisms in WordPress that would fit your use case: custom taxonomies and post metadata.
Since you have already determined that you want something close to mechanics to categories/tags (which are built-in taxonomies) it seems like custom taxonomy is a right fit for your use case.
See `register_taxonomy()` documentation on creating it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "customization"
} |
How to highlight the current page in the nav menu?
I'm customizing a WordPress theme for my school, and I'm a bit annoyed by the fact that the current page in the nav menu is not indicated.
For example:
!enter image description here
You can clearly see that I'm hovering over a page in the nav menu, and that the page I'm hovering over is highlighted, as expected.
However, the page that I'm currently on, called "Arhiva", is not highlighted, and I think that this can be somewhat confusing.
I don't want the current page and the page the mouse is hovering over to be highlighed in the same manner though. I believe that a bold entry text in the nav menu would do just fine to separate the current page from other pages.
How can I achieve this?
Theme's current CSS can be viewed here: < | The Navigation Menus system is adding a lot of classes, including matching current page (rather intelligently, it will even try to detect custom URLs, that were input explicitly).
The simplest class to make use of is `current-menu-item`, but there are quite a few more dealing with parents/ancestors and more.
Codex has them documented at `wp_nav_menu()` > Menu Item CSS Classes. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "theme development, menus, themes, pages, css"
} |
Redirect user after login/registration globally
How it possible to redirect all users, even administrators after login to specific page? And also redirect users after successful registration? Any simplest way? For example I want to redirect users after login, to the "Updates" page of my website. And after registration, to the "Home" page of website. | This code adapted from: Registration Redirect
add_filter( 'registration_redirect', 'ckc_registration_redirect' );
function ckc_registration_redirect() {
return home_url();
}
This code adapted from: Login Redirect
add_filter( 'login_redirect', 'ckc_login_redirect' );
function ckc_login_redirect() {
// Change this to the url to Updates page.
return home_url( '/Updates' );
}
Add the code to the functions.php theme (or child theme) file. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "redirect, login, user registration, wp redirect, wp login form"
} |
How can I get all author written content?
I have a site that needs two different tabs: 1\. all author written content (Posts, comments, CTP) 2\. all author _followed_ content (categories, taxonomies, other users content)
For the first all I could come up with was using unoion on wp_comments and wp_posts filtered by author sorted by date
Have no idea how to do the 2nd one...
Would love some advice | Found out the solution for #1. using WP_Query I can specify multiple post_type and an author ID. which gives all author written data... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "author, sql"
} |
Creating a custom multilingual form
I need to create a special form for my website where users cand specify a series of data including some textfields, combo boxes and sliders (from 0 to 100). Also I need this form to be qTranslate compatible, for my website is multilingual.
What would be the easiest, cheapest approach for this?
I tried the lite version of Ninja Forms plugin but it offers very few form element types.
I also started creating my own template with the form elements but I don't know how to make it work with qTranslate. And I'm thinking this solution is maybe reinventing the wheel and there's a fastest approach than programming it myself. | > What would be the easiest, cheapest approach for this?
Simple, create one form per language.
In `functions.php` or, preferably, as a custom plugin:
add_shortcode( 'my-lingo-form', 'shortcode_wpse_98360');
function shortcode_wpse_98360()
{
$lingo = your_language_detection_method();
switch( $lingo )
{
case 'en':
echo do_shortcode('[form-en]');
break;
default:
echo do_shortcode('[form-other-languages]');
break;
}
}
In your post or page: `[my-lingo-form]`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "forms, translation, plugin qtranslate"
} |
Using post_class to style posts indivdually
I have a homepage on which I want to display the latest post different from the other posts. I haven't used `post_class` and I am not sure how to.
Would I be able to achieve what I want using `post_class`? | You should be using `post_class` (and `body_class` for that matter) but you don't need it for this. Alter your Loop on your home page to conditionally format the first post.
$first = (!is_paged()) ? true : false;
if (have_posts()) {
while (have_posts()) {
the_post();
if ($first) {
// code to format the first post
$first = false;
} else {
// code to format all the other posts
}
}
}
If all you need is a small change that can be made via CSS then you can pass `post_class` a parameter.
$first = (!is_paged()) ? 'is_first' : 'not_first';
if (have_posts()) {
while (have_posts()) {
the_post();
echo '<div ',post_class($first),'>';
// the rest of your Loop
echo '</div>';
$first = 'not_first';
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, post class"
} |
Adding a template in WPTouch
I am creating a mobile version for a site. For that I am using WPTouch not WPTouch-Pro. Now I want to add a form in my page.
For desktop version I used template to add form. But in mobile version it's not working. When I exit mobile version form is present in my page. I saw some post which suggest to add child theme and its for WPTouch-Pro.
Since I am new to wordpress I don't have any idea how to solve this problem. | As WPTouch uses its own theme, we can't hardcode certain functionality inside the regular theme, neither in a page/post template nor `functions.php`.
So, a custom plugin is needed and the desired output made out of a Shortcode.
Also, make sure WPTouch `Restricted Mode` is turned off in _Advanced Options > Advanced Settings_. But probably this restricted mode can live together with a Must Use plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, mobile, plugin wptouch"
} |
Is the wordpress user-model changed in wpmu?
I'm running wpmu on heroku using a postgres extension. It works great, but I have a plugin that needs to get the userId based on the e-mail-adress. This is how it does it:
$sql = 'SELECT id FROM ' . $wpdb->users . ' WHERE user_email=\'' . addslashes($from) . "' LIMIT 1;";
$user_ID = $wpdb->get_var($sql);
$wpdb->get_var($sql) returns nothing. I'm trying to figure out why. | The plugin should use the API, not some made-up SQL. `addslashes()` is not safe enough anyway.
$user = get_user_by( 'email', '[email protected]' );
echo $user->ID;
Besides that, the user tables are almost the same, there are just some tighter restrictions for user names in multi-site, because new sub domains could be made from the names. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, multisite, database"
} |
Post preview gives 404 when permalinks are purely date based
I have an issue pertaining specifically to the situation in which permalinks are set to be based only on publication date. My permalink structure is as follows:
/%year%%monthnum%%day%/
When I try to preview a post, I get 404. The issue does not come up when I add other URL tags to the structure, like post ID or post name.
I have already tried to diagnose the issue and one thing that came up was that Wordpress may be treating URLs consisting only of date tags as date archive pages. Indeed, is_date() returns TRUE when a post page is displayed.
Is there a way around it that does not involve changing permalink structure? Thanks for help. | I will sum up my findings for future use by others:
1. When using permalink structure that uses only date tags, Wordpress is unable to identify a unique post because there may be more posts in any given day.
2. For this reason Wordpress treats URLs with date based tags only as date archive pages.
3. Given the permalink structure, Wordpress still allows for previewing of posts with present or past publication date (published or drafts) and posts that have publication date set for the future **and** are still drafts. Previewing posts that are scheduled for future publication and are not drafts, is impossible - they will return the 404 error.
@Milo, @t3los, thanks for your input. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "permalinks, 404 error, date"
} |
Pull GetOption() variable into jQuery dynamically created html
I have a page with the following markup in the site theme footer:
<div id="modalpopup"><div id="inside"></div></div>
I have a variable in the WP db I can retrieve via `GetOption()` which I would like to stuff into that `div#inside` on page load via jQuery.
When I've done AJAX before it's always been upon the user hitting a button to cause a POST, but this is a bit different so I'm kinda stuck.
I need to retrieve that variable from the db, send it to the jQuery function and then have the HTML generated rendered all -before- the page loads.
Ideas? | You would still do this with AJAX, except that instead of firing on some event like a 'click', or 'hover', or `submit`, you would fire the Javascript function on `jQuery(document).ready` instead. That will execute immediately on page load. It doesn't let you execute the code _before_ the page loads as your question states but you can't run Javascript before the page loads. Javascript runs client-side, in the browser. The page has to load in order for that to happen. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, jquery, ajax, options"
} |
How to deal with the confliction between PHP-Markdown and MathJax?
I use PHP-Markdown plugin in WordPress. In order to show the formula beautifully, I add some code to use MathJax.
Like this:
<script type="text/javascript" src="
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"HTML-CSS": { availableFonts: ["TeX"] }
});
</script>
But something wrong happens. Once my formula contains at least two underlines, the MathJax doesn't work. Such as `$$P_1, P_2$$`, and the words between the two underlines will be transformed to italic.
The formula will be transformed by PHP-Markdown first, and it can't be transformed by MathJax again.
Could you help me? | I'm not sure this is a real answer, but have you tried PHP-markdown-extra (by the very same Michel Fortin)?
At least for me (using Mark Jaquith's markdown-on-save plugin) your example is not a problem.
But Markdown-extra is not perfect either and I've seen some other quirks with respect to emphasis, e.g. Let $(y_n)_{n\in \omega}$ enumerate ${ x_i: i \in \bigcup_{n\in \omega} A_n} $ will trip it up. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, latex, markdown"
} |
WordPress plugin installation
I am using the simple `add_filter` function to output the content.
add_filter('the_content', 'my_name');
function my_name( $content ){
// code
return $content;
}
When I activate the plug-in output of the function `my_name` is shown in all pages. How can I restrict the output to only one page? | Add this code and replace `yourpagename` with the your page slug on which u want this filter to execute
function my_name( $content ) {
global $post;
if ( $post->post_name == 'yourpagename' ) {
return $content;
}
}
add_filter( 'the_content', 'my_name' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, php, plugin development"
} |
Add Additional File Info (jpeg compression & file size) settings to Edit Images Screen
On the WordPress Edit Image Screen, I'd like to add a label to show the current compression level and byte file size of the image.
Any ideas how to tap into this screen and echo this data?
The current settings show:
* Date
* URL
* File name
* File type
* Dimensions
I'd like to ad
* File Size
* File Compression (echo the current jpeg_quality setting) | You can try to use the `attachment_submitbox_misc_actions` filter to add more info to the box. Here is an example for the filesize part:
!enter image description here
add_action( 'attachment_submitbox_misc_actions', 'custom_fileinfo_wpse_98608' );
function custom_fileinfo_wpse_98608(){
global $post;
$meta = wp_get_attachment_metadata( $post->ID );
$upload_dir = wp_upload_dir();
$filepath = $upload_dir['basedir']."/".$meta['file'];
$filesize = filesize($filepath);
?>
<div class="misc-pub-section">
<?php _e( 'File Size:' ); ?> <strong><?php echo $filesize; ?> </strong> <?php _e( 'bytes' ); ?>
</div>
<?php
}
The default file info is displayed with the `attachment_submitbox_metadata()` function through this action:
add_action( 'attachment_submitbox_misc_actions', 'attachment_submitbox_metadata' );
in the file `/wp-admin/includes/media.php` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugin development, media library, compression"
} |
including image assets in widget
I've written my first simple WP widget-- it all works fine, but I'd like to dress it up a bit, and add an image / logo in the widget display code.
How do I package the widget (which is just a single PHP file) with the image, and where will the image be stored in the WP site (so I can create the img tag link correctly)?
I know I could easily host the image externally and just "hotlink" to it from within my widget, but that seems a little hackish.
Thanks | It sounds like you'll need the `plugins_url()` function which generates the URL for the plugins directory and can handle any alternate configuration (such as if you moved it to the `/mu-plugins/` directory, a personal favorite of mine). The Codex documentation is good, but here's a quick example.
* Let's say you're making this in a plugin that in `/wp-content/plugins/my_awesome_widget/`.
* To make the example slightly more interesting, you store all associated images in `/wp-content/plugins/my_awesome_widget/assets/images/`.
* Your image is called `company_logo.png`.
* In the root plugin directory is your main plugin PHP file which needs to reference the widget.
So to get the image, you'd use a snippet like this:
<?php printf(
'<img src="%1$s" alt="{YOUR COMPANY} logo" />',
plugins_url( '/assets/images/company_logo.png', __FILE__ )
); ?>
If all goes well, that will print out:
<img src=" alt="{YOUR COMPANY} logo" /> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "images, widgets"
} |
How to remove thumbnail sizes for specific post type on a child theme?
The theme I'm using includes a slideshow that generates an additional 4 image sizes for every image that is uploaded. I don't need to have all those images being generated for every image.
Is there a way to remove the slideshow thumbnail sizes for a custom post type in my child theme?
Thanks | I think it might be possible, try adding this to your child theme's functions.php
add_action('init', 'remove_plugin_image_sizes');
function remove_plugin_image_sizes() {
remove_image_size('image-name');
}
Here is the documentation: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, child theme, post thumbnails"
} |
Split function "the_tags" in 2 columns
I have the following function that returns the tags of the current post:
<?php the_tags( '<ul> <li>', '</ li> <li>', '</ li> </ ul>' ); ?>
Example:
!enter image description here
Is there any way to split the result into 2 columns?
Would return something like this:
!enter image description here
Any hint is welcome. Thank you friends! | Use `get_the_tags` instead of `the_tags` to grab an array of tags, and `array_chunk` to split it. You will then need to build a loop to display the tags.
$tags = get_the_tags();
if (!empty($tags)) {
$tags = array_chunk($tags,ceil(count($tags)/2),true);
foreach($tags as $v) {
echo '<ul>';
foreach ($v as $tag) {
echo '<li><a href="'.get_tag_link($tag->term_id).'">' . $tag->name . '</a></li>';
}
echo '</ul>';
}
}
## Reference
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "tags, columns, split"
} |
wpautop on section
I removed automatic formatting in my WP site by adding this to functions.php:
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
Now I need to add it back into one section only. On page.php, I want to replace the_content with wpautop formatted content.
I replaced this:
<section class="post-content clearfix" itemprop="articleBody">
<?php the_content(); ?>
</section>
With this:
<section class="post-content clearfix" itemprop="articleBody">
<?php
$c = the_content();
$format_c = wpautop( $c, false );
echo ($format_c);
?>
</section>
Unfortunately it is not adding paragraph tags here. Can anyone help me to add paragraph tags only at this location in my theme? I do not want them in the page custom templates or any of the posts.
Thanks! | Please try this
$c = get_the_content();
instead of:
$c = the_content();
since `the_content()` will _echo_ the content instead of _returning_ it.
Or try this
<section class="post-content clearfix" itemprop="articleBody">
<?php add_filter( 'the_content', 'wpautop' ); ?>
<?php the_content(); ?>
<?php remove_filter( 'the_content', 'wpautop' ); ?>
</section> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, wp autop"
} |
Fix Admin Dashboard Posts tab
I have WordPress v3.5.1 and using a theme from WPZoom. I added an SEO plugin called WordPress SEO which in turn added 4 more columns to my Posts Admin table which caused the columns to squish together making it very hard to see all the posts now. I have tried to change the CSS in the admin CSS but that does not help at all yet when I do change it using Firebug it helps. how can I fix the squished columns?
You can see a copy of the image for better understanding at < | You can control columns in most admin panels by clicking `Screen Options` at upper right of the screen and (un)checking them as you want.
This is however saved individually for user and to get rid of column for all users would involve writing code to hook into internals and unregister it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin"
} |
Why don't some template tags work when querying information on single.php?
I'm trying to fetch content about the current post into the header.php of my theme (to dynamically insert Facebook OpenGraph Metadata).
Since I'm on a single post page, shouldn't it be able to run functions like `the_content()` or `wp_get_attachment_thumb_url()`?
<?php if (is_single()) {
<meta property="og:title" content="<?php echo get_the_title()." - Advocate Daily" ?>" />
<meta property="og:description" content="<?php string_limit_words(the_content(), 15);" ?> />
<meta property="og:image" content="<?php echo wp_get_attachment_thumb_url(); ?>" />
<?php } ?>
In the above example, the first tag works, but the content of the other two isn't outputted.
Does this mean certain template tags needs to be in the
if ( have_posts() ) : while ( have_posts() ) : the_post();
loop? Do I need to declare this loop again in the header? | Consider this snippet here to accomplish your task. If you add it to your `functions.php` file, the Open Graph tags will be populated automatically as part of the `wp_head` action. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "functions, loop, facebook, template tags"
} |
wp_allow_comments checking for blacklisted words effectively
I have a big list of prohibited words on the DB. The problem Im running to is that no comment is getting through. They are all getting sent to spam. I was looking at comment.php and found the functions that are handling this. I dont wanna modify the core functions but to write my own. I tried something like `add_action( 'wp_blacklist_check', 'my_wp_blacklist_check');` and pad the words with spaces, so words like 'bi' dont conflict with... let say, the word 'combination'.
Obviously my action did not work is there something Im missing? a different hook or something?
Thank! | `wp_blacklist_check` is an action - it does not return results and does not influence logic.
Hook you want is `pre_comment_approved` filter that gets two arguments - `$approved` (`1`, `0` or `spam` ) and `$commentdata` with comment info.
Use data for your custom processing and return changed `$approved` outcome if needed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "options, moderation"
} |
Links In Sidebar not displaying
Ive placed a link in the sidebar, however its not showing up at all!
Any ideas? The link is the blackburn text in the post.
<
thanks Kirsty | I'm guessing that text is an excerpt - and so any mark-up will be stripped out. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "links"
} |
How to define the template priority between built-in categories and custom taxonomies?
Let's say I want to create a custom template for my taxonomy `customtax`.
This is pretty simple, I just create a `taxonomy-customtax.php` in my theme directory.
Now, I'ld like to query a built-in category with one term of my custom taxonomy, like so:
www.example.com/?customtax=x&category_name=y
The problem here is that Wordpress always uses the `archive.php` (or `category.php` I think) instead of my `taxonomy-customtax.php` template.
Is there a way to invert this behaviour? | You can _tell_ WordPress what template file to use with the `template_redirect` hook.
add_action( 'template_redirect', 'wpse98738_taxonomy_redirect' );
function wpse98738_taxonomy_redirect() {
if( 'x' == $customtax && 'y' == $category_name ) {
include( get_template_directory() . '/taxonomy-customtax.php' );
// if you're using a Child Theme, use the following line instead:
// include( get_stylesheet_directory() . '/taxonomy-customtax.php' );
exit; // so that WP quits looking for templates to load
}
}
### Reference
Codex pages for:
`template_redirect`
`get_template_directory()` / `get_stylesheet_directory()` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "template hierarchy"
} |
How can I get the name of term post meta value which equals term id
I have a custom taxonomy (location) that is being populated automatically by an advanced custom field on user save. The issue is that it saves the term_id in the postmeta meta_value field. When I echo that field in my archive or taxonomy template it obviously shows me the term_id and not the actual term name (ex. I get 41, instead of California displaying). I have tried multiple things to get this to appear and days and basically any query I do ends up just a blank space displaying on my archive/taxonomy page. Can anyone assist me in how I might retrieve the term name from the term_id being outputted?
Thanks in advance! | You can use `get_term_by` to retrieve a term by its ID:
$term_id = 123;
$term = get_term_by( 'id', $term_id, 'location' );
if( $term ){
echo $term->name;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, terms, advanced custom fields"
} |
wp_head() - list hooked actions with priorities?
I'd like to add something to `wp_head()` but I'm aiming precise location (like after style.css but before rtl.css and before my other custom script). I'm wondering if it's possible to list everything that is attached to `wp_head()` in execution/display order anyhow?
I know that I can pass priority/order parameter to `add_action` but I need to know what number will that be.
add_action( 'wp_head', 'my_function', 10 );
It all starts with `10` but somehow rtl.css seems to be always after style.css. Is it `11` maybe? How do I find that out? | While you can practically control order of hooked things by priority, it's not always the right tool for the job.
In case of styles you should be using appropriate `wp_enqueue_style()` function which allows you to easily set up elaborate dependencies which will be automagically processed by WP to produce desired order of styles output.
Unfortunately while there is analogous `wp_enqueue_scripts()` for scripts, you cannot cross-depend scripts and styles like your question indicates. However it is common practice to not start JS execution until page has fully downloaded, so in most cases explicit depending on CSS should not be necessary. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp enqueue script, headers, wp head"
} |
Removing meta boxes: remove-meta_box() or unset()?
I've seen two ways to remove meta boxes: remove_meta_box() and unset().
function TEST_remove_dashboard_widgets(){
remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' );
}
add_action('wp_dashboard_setup', 'bmc_remove_dashboard_widgets');
vs.
function TEST_remove_dashboard_widgets() {
global $wp_meta_boxes;
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
}
add_action('wp_dashboard_setup', 'bmc_remove_dashboard_widgets');
remove_meta_box seems better since it's clearly intended just for that, but I've also seen the unset formulation in several places.
Why would I use one vs. the other? | When in doubt use the API.
Let’s say the structure of `$wp_meta_boxes` will change or go away one day.
`remove_meta_box()` will still work, because the API is a contract between core and developers. Unsetting some keys in a global variable might break.
`unset()` is easier to write when you want to remove a whole group: `unset($wp_meta_boxes['dashboard'])` is clearly simpler than running through each separate box. But shorter code is not always better, so this should not be used in public code.
Note, both methods actually work differently: `unset()` removes an element from the array, while `remove_meta_box()` set the elements value to `FALSE`:
foreach ( array('high', 'core', 'default', 'low') as $priority )
$wp_meta_boxes[$page][$context][$priority][$id] = false;
Other plugins might rely on the existence of that element – and break after you have used `unset()`. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "metabox"
} |
Enable comments for post when comments meta box removed
I've hit the issue described in '11:
"Enable comments for post with comments meta box removed" and I'd like to ask for your help to adapt the mentioned there code to the current wordpress version.
I have a custom post type that must have comments enabled and _contributors_ must not be able to disable comments.
I've enabled comments in Settings->Discussion and removed the `commentstatusdiv` meta box with `remove_meta_box()`. After that I've figured out that comments is unset when the meta box is disabled.
I am looking for the way to enforce the comments now. | Filter the `'comments_open'` check. It happens inside of the function with the same name, and that function is called in a theme usually like this:
comments_open() and comment_form(
array (
'comment_notes_after' => ''
)
);
This is how the filter works:
add_filter( 'comments_open', 'wpse_98775_comment_check', 10, 2 );
function wpse_98775_comment_check( $open, $post_id )
{
if ( $open )
return $open;
if ( 'my_post_type' === get_post_type( $post_id ) )
return TRUE;
return $open;
}
You could create a custom plugin with this snippet. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, posts, comments, user roles"
} |
Display random posts, but omit the post it is on?
I am trying to have a section under a single post where it displays completely random posts. I got everything working, but every once in a while one of the random posts that get displayed is the actual post that it is on (the single).
Here is my code:
<?php
$args = array( 'numberposts' => 3, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<?php endforeach; ?>
Is there anyway to not have it ever display the post it is on?
Thank you. | Check to see if you have a post ID (which you should on a single post page but I am not sure if this is in `single.php` or some other template like `index.php`) and add that to the `$args` if you do.
$args = array( 'numberposts' => 3, 'orderby' => 'rand' );
if (is_singular() && isset($post->ID)) {
$args['exclude'] = array($post->ID);
}
$rand_posts = get_posts( $args );
## Reference
<
<
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, posts"
} |
Print out one of 2 post category
I've been trying for quite a few hours to get something to print out in loop: post has 2 categories, one of them is `prace` (slug) and I need the other one printed. If it isn't too much to ask.
Tried just about everything with categories I could but can't get any further due my lack of knowledge of working with arrays in PHP.
Thanks in advance. | If I understand your requirements correctly:
$terms = wp_get_post_terms( $post->ID, 'category' );
echo $terms[1]->name;
You can see what other values are returned by `var_dump`ing `$terms`. The above assumes that you are using the category taxonomy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "posts, categories"
} |
Custom Role does not have access to dashboard
I was just adding a custom role by using the add_role() function. Here is the code below:
add_role('user', 'User', array('read'));
I figured this would give the same level of access as the subscribers role. Technically I want them to be the same but I don't want to use the subscribers as a role for certain users because there will be different access between the two.
However, although, from what I read on the wordpress codex site, the subscribers has only one capability and that is to 'read' it has access to the dashboard and can edit their own profile. My custom role cannot. I get the following message when going to the admin panel.
_You do not have sufficient permissions to access this page._
Why is that? Hoe do get the right permissions to do this?
Thanks, Joe | You have to give the capability a true or false, like this:
`add_role('user', 'User', array( 'read' => true ));`
To fix it, first remove the role and than re-add it again.
remove_role('user');
add_role('user', 'User', array('read' => true));
< | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 6,
"tags": "dashboard, permissions"
} |
For Each +1 Wordpress Loop
Im using a loop to make a slider. My code is
<?php
query_posts( array( 'post_type' => 'my_gallery', 'author'=>$author->ID ) );
while( have_posts() ) :
the_post();
$imagethum = eh_postImage(115, 70);
?>
<a data-slide-index="0" href=""><?php echo $imagethum; ?></a>
<?php endwhile; ?>
I need the `data-slide-index="0"` attribute to increase by 1 for every post in the loop so the output appears as...
<a data-slide-index="0" href="">
<a data-slide-index="1" href="">
<a data-slide-index="2" href="">
<a data-slide-index="3" href="">
<a data-slide-index="4" href="">
<a data-slide-index="5" href="">
after printed
Some kind of `for each` statement here? | try yo use the build-in loop counter:
<a data-slide-index="<?php echo $wp_query->current_post; ?>" href=""><?php echo $imagethum; ?></a> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop"
} |
Post Terms As Class Name For Full Calendar Events
I have implemented Full Calendar via json with my Wordpress custom post types.
All is fine except I want to add the taxonomy term of the event / post to the 'className' of the event object but cant seem to get it working, can someone please take a gander at my implementation see where I am going wrong?
I cant seem to get my pasted code formatting legibly as such I have added a link to a pastebin, apologies, can be see here
get_single_term relates to a custom function to output the first term of the taxonomy as follows ....
function get_single_term($post_id, $taxonomy) {
$terms = wp_get_object_terms($post_id, $taxonomy);
if(!is_wp_error($terms))
{
echo $terms[0]->name;
} }
Thanks for any advice | You are using `get_single_term` in a way that would require it to return a value...
$term = get_single_term($post->ID, 'course_locations');
... but you have written it in such a way that it `echo`s a value. You should have...
function get_single_term($post_id, $taxonomy) {
$terms = wp_get_object_terms($post_id, $taxonomy);
if(!is_wp_error($terms))
{
return $terms[0]->name;
}
}
I noticed a couple of other things not directly related to the question but worth mentioning.
1. You really should be using the AJAX API. `include`ing `wp-load.php` like that is a kind of hack, in my opinion, that is no longer necessary. It is also prone to error. Imagine if someone were to move one or more of the content directories.
2. You should really learn to indent your code. You are going to run into all kinds of headaches trying to debug "flat" code like that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "events, calendar"
} |
Enable "My blogs" in a custom installation
I'm trying to make a little blog network that functions like wordpress.com, where I can create and admin multiple blogs with a single user (or share blogs between users).
I've tried to do that by simply following this guide, but when I tried to create a new site, it created another user with it.
How can I enable the **_my blogs_** function from wordpress.com on a custom installation? | If you create the new blog using your email address, it will be owned by your user. Because you are acting as the super admin, it assumes you are creating for a new user.
Not entirely sure what you mean about my blogs, but if you follow the steps above then the new blog will appear in the drop down admin bar when you are logged in and browsing any site / admin panel as on WP.com. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite"
} |
Category archive is displaying all posts rather than the specific category
Here is my loop code for index.php . I do not have an archive or category.php right now. This is very basic.
$temp = $wp_query;
global $wp_query;
$wp_query = new WP_Query();
$wp_query->query('posts_per_page=20'.'&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();
I have about 10 posts split up into different categories.
When I click /category/category-name it just lists all posts rather than filtering by category.
Can someone help me out if they know the solution?
Thanks. | You are overwriting the query that loads with the page (which you saved to $temp) - why not just use the one that loads with the page:
while(have_posts()) : the_post();
// put the post here
endwhile; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, loop, archives"
} |
Why do you need an unlikely integer in paginating?
The `paginate_links` Codex function reference has some sample code that's being reposted all over the net.
It has a section that uses a variable called `$big = 999999999; // need an unlikely integer`:
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
And is used in `str_replace` in the `echo paginate_links` function.
Is this some form of encapsulation? | Note the `get_pagenum_link( $big )`: This will create an URL ( _not_ a link) based on the number provided in the first parameter.
That function is used to get the basic pattern for the URL, and the high integer is used here, because:
1. You must provide an integer as argument.
2. The resulting URL is filtered with `apply_filters('get_pagenum_link', $result)` and might be changed by plugins. This risk is slightly higher for numbers _matching existing pages,_ for example when a plugin implements separate titles for sub-pages.
So this is just a … dirty convention, a signal to other plugins: Don’t change that please! I think `PHP_INT_MAX` would have been better, but still ugly. And I wonder how many plugin developers _know_ that.
The number is then replaced with the placeholder needed in `paginate_links()`.
What you see here is an **incomplete API**. Try to learn something from this example – do not release incomplete APIs, or your docs will look embarrassing. :) | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 17,
"tags": "pagination"
} |
Remove Links from Login page
I want to remove all the links from my network login page ("Register","Lost your password" and "Back to site") how can i do that?
!enter image description here | I am not sure there is a way to suppress all these links, but you can hide them with CSS:
add_action( 'login_head', 'hide_login_nav' );
function hide_login_nav()
{
?><style>#nav,#backtoblog{display:none}</style><?php
}
### Result:
!enter image description here | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "customization, login"
} |
List the categories under custom taxonomy
I have a problem here, I registered a custom post type and I named it 'recipe' then I created a custom taxonomy under the post type, I named it 'recipe category'. Now I want to display the of categories under that custom taxonomy, but unfortunately I have no luck.
I tried this code
<?php
$taxonomy = 'recipecategory';
$tax_terms = get_terms($taxonomy);
?>
<ul>
<?php
foreach ($tax_terms as $tax_term) {
echo '<li>' . '<a href="' . esc_attr(get_term_link($tax_term, $taxonomy)) . '" title="' . sprintf( __( "View all posts in %s" ), $tax_term->name ) . '" ' . '>' . $tax_term->name.'</a></li>';
}
?>
</ul>
but it displays nothing, what's wrong with my code? did I missed something. Almost forgot to mention, I am using the plugin Custom Post Type UI | The problem can only be one of the following:
1. Your taxonomy "recipecategory" does not exist.
2. Your taxonomy has no terms.
3. None of your recipecategory terms have any posts. In this case, make the following change:
`$tax_terms = get_terms($taxonomy, array('hide_empty' => false));`
This should work as it will override the default setting, which is to ignore empty terms.
foreach($tax_terms as $term_single) {
$term_single->slug;
$term_single->name;
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 7,
"tags": "custom post types, custom taxonomy"
} |
Cannot select certain authors for posts after import
I just consolidated a couple standalone WordPress installs into one Multi-site install. After importing posts into each site accordingly, I am unable to edit a post or page, and select a different user.
There are four users on the site, and I'm only able to select two of the four users as the post author.
Any idea why this would be happening? I'm pretty savvy with WordPress, but this one puzzles me.
Any Ideas? | I found the issue, thanks to `@Toscho` giving me the spark of an idea. We are using custom user roles and capabilities. It had something to do with the User Role Editor plugin. Deleted the custom role, and created a new one, reassigning all capabilities. Then updating all users to the newly created user role. Problem fixed.
Not sure why that happened, but for anyone else who may use this plugin or run into this issue, this is a fix that worked for me. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, multisite, users, author, import"
} |
option_active_plugins filter not working
I added a filter for option_active_plugins to keep most plugins from loading on an admin page. Confirmed to be on the right page and to be returning a properly altered array, but it's having no effect on which plugins are being included on the page.
Tried high numbers for filter priority. No effect. Any ideas? | OK, duh: I needed to have my plugin in the /mu-plugins dir to make its filter available early enough for `function wp_get_active_and_valid_plugins()`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "filters"
} |
Make editor required for post from frontend
I am trying to build a content submission form on the front end of my site, and I am using `wp_editor` to render visual text editors for my users, so they can make bold text and lists and stuff like that. The issue is that I can't figure out how to make the wp_editor a required field in my form. I know I can do the following for a standard text area.
<textarea id="content" name="content" required="required"></textarea>
that will make the browser itself recognize that it is a required field. No JavaScript jQuery or anything else needed. I need to accomplish the same thing with wp_editor, which does generate a textarea. | You can add a filter to the editor html
add_filter( 'the_editor', 'add_required_attribute_to_wp_editor', 10, 1 );
function add_required_attribute_to_wp_editor( $editor ) {
$editor = str_replace( '<textarea', '<textarea required="required"', $editor );
return $editor;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "forms"
} |
Get TOP x Tags from selected posts
I need help on this, the case is I want to get TOP X tags from user post. For example user A wrote 50 post, i want to show TOP 5 tags from that user post, It 's for displaying user interest.
second important thing is i m already have the post ID's selected. $pids = array(123,345,323,456,789);
Thank you.
* i found interesting code here, but just by date: Display list of most used tags in the last 30 days | With an array containing the post IDs its easy
$post_ids = array( 167, 774, 787, 358 );
$tag_all = array();
foreach ( $post_ids as $post_id ) {
$tags = wp_get_post_tags( $post_id, array() );
foreach ( $tags as $tag )
array_push( $tag_all, $tag->name );
}
$result = array_count_values($tag_all);
arsort( $result );
$result = array_slice( $result, 0, 5 );
echo '<ol>';
foreach ( $result as $tag => $count ) {
printf( '<li>%s (%d)</li>', $tag, $count );
}
echo '</ol>';
Walk over the post IDs, get the tags of each post. Add the tags to a result array (`$tag_all`). Then counting the values (`array_count_values()`), this gives you an array with `key => value` (`key` = tag, `value`= count). Now just sorting the result array (`arsort()`) and get the first 5 elements (`array_slice()`).
Create a nice outpout and finish. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tags"
} |
Is a *.wordpress.com blog easy to migrate?
As a student software developer who is about to graduate, I find it is time to start my own blog. I've been told it is important to make a name for yourself, to stand out from the rest. Therefore I decided to make a Wordpress website.
Since I live in Belgium, I would like a `.be` domain. But, I'm new to Wordpress and I want to go full-on with my own theme from the start. However, I would like to avoid the cost of my domain during the development phase of my website, so I'm planning to create it on the free `*.wordpress.com` domain first.
## My question:
If I do this, will I have an easy time migrating everything to my own domain? Which features of my web hoster (server, database, disk space, etc) should I look for specifically, to make the process go smoothly? | Its simple..
## Export
!enter image description here
Just check this page to export your blog data..
<
## Import
Install a fresh wordpress.. Then import it..
!enter image description here
<
## Please note:
wordpress.com uses the same software downloaded from wordpress.org.. They just using it as multisite..
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wordpress.com hosting, migration, domain"
} |
How to get type of archive whether it is post or date or category archive?
using function `is_archive()` we can know whether it is archive page or not.
But if it is archive page how can i find whether it is author archive page or category archive or date archive.
I have found this code in wp-includes/query.php
if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
$this->is_archive = true;
but dont know how to use it in wp_head action.
Based on archive page category or author or date archive, i want to out put specific meta tags in header.
Any help???
Thanks in advanced.
wordpress.stackexchange.com rocks!! | Use just the functions, not the object properties:
if ( is_post_type_archive() or is_date() )
There are many conditional functions (returning `TRUE` or `FALSE`) for exactly these cases. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "archives, conditional tags, conditional content, custom post type archives"
} |
How to display WP Query filters?
I'm wondering if there is a way to display current WP Query filters. I wrote a function that is supported to delete all posts and it does but when I'm using WPML and it filters posts by language then it does not remove non-English posts.
I thought that using `'suppress_filters' => true` will help but will this cause any drawbacks? What other filters are applied to WP Query? Can I display them somehow? | There's a global variable called `$wp_filter` (you can see examples of it all through the source of `/wp-includes/plugin.php`. This probably isn't the WordPress Way to do it, but you could try something like this:
global $wp_filter;
var_dump( $wp_filter );
...but note the caveat on < \-- "Accessing other globals besides the ones listed below is not recommended." (And `$wp_filter` isn't in that list.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, wp query, plugin wpml"
} |
Output posts with same name as tags?
If someone puts a post on my site, they usually do that with some tags. If someone posts a post with the tag "hello", I want it to output that tag after my content and let it link to the archive page where it queries to see if there is another post with the same tag --> this already works!
What I now want is this: say there is also a post named "hello", now I want to get both the described tag above as well as a "see also [post] hello"... So I use the given tag as it does in default, but now I want to output the same tag again, but this time linking to the post with the same name... Is this possible? If so, how?
I tried editing the code that is given here: Redirect Tag to Post with the same name but I do not know how I can output the same tag, that does two different things. | You can use the get_page_by_title function as described by the codex here < Here is an example of getting the title of a post. By default, it's looking for a post type of 'page':
$current_post = get_page_by_title("certain title", OBJECT, "post");
echo "<a href='" . $current_post->guid . "'>{$current_post->post_title}</a>"; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, tags"
} |
WP_Query meta_query by array key
I have a custom post type with its meta in an array. What I need to do is query based on the value of a key in that meta array.
$args = array(
'post_type' => 'my-cpt',
'posts_per_page' => -1,
'orderby' => 'meta_value', // Sort by this value
'meta_key' => 'my_meta_array', // Sort by this meta key
'meta_query' => array(
array(
'key' => 'key here', // WHAT GOES HERE?
'value' => array( 'meta-value' ),
)
)
);
$query = new WP_Query( $args );
What goes in the meta_query key, if my key is my_meta_array[key]?
FYI: the keys are indexed by my_meta_array[key], stored in the db via update_post_meta( $post_id, 'river_helpers', 'my_meta_array' ), and retrieved via get_post_meta( $post->ID, 'my_meta_array', true ); | You can't do that. When you save postmeta (or any other meta, for that matter), WordPress runs it through `maybe_serialize` which turns objects and arrays into serialized data. When it gets pulled back out, it is run through `maybe_unserialize`.
Serialized data looks something like this:
a:1:{s:3:"one";s:3:"two";}
In other words, what get's stored cannot be queried in the way you want. The best you could do is a `LIKE` query, which will be unreliable at best and less performant. Just use `LIKE` as the `compare` argument of your meta query.
Your best bet: rethink how you store meta and move whatever `key` is to its own entry. Meta tables in WordPress are key value stores, it's not unreasonable to store multiple meta values per post type or plugin. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query"
} |
Why do previews work in one browser, but not another?
I keep having an intermittent issue where the admin bar disappears from a wordpress site I often use, when using my main browser (Google Chrome). I can access /wp-admin/ no problem, and another problem is that post previews will not work, instead showing me the 404 page.
Safari, however, works just fine. What can I do to get Chrome to behave properly again? | I still don't know what the exact cause was, but deleting cookies for the specific site fixed the problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin bar, previews, browser compatibility"
} |
Twitter feed is showing blank in WP site
I am using themefuse WP theme and facing this problem.
<
Can someone please suggest if I need to use some other attribute. I am not finding any help on ThemeFuse site.
Thanks | It is very likely because you are using the old Twitter API, for example:
<script type="text/javascript" src="
You will need to update your code to the new API:
This requires that you edit the code of the theme. Many themes suffered this issue for a few months ago when Twitter made their changes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, themes, feed, twitter"
} |
Include "registration.php" for custom registration form?
I’m creating a custom registration form for my website. Every tutorial has this call in the form
require_once(ABSPATH . WPINC . '/registration.php');
I’ve read that `registration.php` has been depreciated quite a long time ago. Which file must be called upon, what is the proper way? | If you look at the source of the file you can see that it doesn't do anything even if you were to include it except add a warning that "This file no longer needs to be included". So those tutorials are out of date. You don't need to include it.
The file you actually need to `include`, if any file at all, depends on what you want to do _exactly_ , and you don't explain that in the question. A number of registration functions are in `wp-login.php` which is very inconvenient because you can `include` that file to get at the functions without also getting a bunch of `echo`ed HTML as well. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "user registration"
} |
If post exists, make it a comment in existing post with same name?
Is it possible to make a comment out of a post that already exists (with the same name). For example, if the post 'Hello World' exists and a users posts another 'Hello World' post, it should make the second post a comment beneath the first post... How can I do this? | You can use get_page_by_title < to check if another page/post is using the same title. If so, get the content of that post and insert it using wp_insert_comment, and delete the original post with wp_delete_post. Finally, glue all these together inside the save_posts action hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, comments, title, function exists"
} |
Get names of authors who have edited a post
How can I call the usernames of people that have edited a post?
I know I can use `get_the_modified_time` to display the time the post was last modified, is the same possible with the list of users that edited it? | The WordPress function **`get_the_modified_author()`** will give you the author who last edited the current post.
But if you want to list all the users that have edit the current post, you could try:
function get_the_modified_authors_wpse_99226(){
global $wpdb;
$authors = array();
$results = $wpdb->get_results( $wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE (post_type = '%s' AND ID = %d) OR (post_type = 'revision' AND post_parent = %d) GROUP BY post_author", get_post_type( get_the_ID() ), get_the_ID(), get_the_ID() ) );
foreach($results as $row){
$authors[] = get_the_author_meta('display_name', $row->post_author );
}
return implode(", ", $authors);
}
This function will give you a distinct comma seperated list of the users that have edit the current post (i.e. their display name). This should also work with custom post types. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "posts, front end"
} |
Woocommerce Emails not being sent
I would like to know the best way to debug email issues in woocommerce when the mails are not being sent for any account/Order related processes.
Thanks | This sounds like your site is unable to send emails from the web server or your emails are being blocked by spam filters. Try setting up a free account at one of the two services I've linked to below and install their WordPress plugin and see if this fixes your email issues.
Sendgrid
Mandrill | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, email"
} |
WordPress & External Page: 404 error in IE and some others
I'm working some API. Core is WordPress. Okay, let me paste a sample:
<?php
include_once('../wp-blog-header.php');
$roll= esc_attr($_GET['roll']);
if ( $roll != "" ) {
$args = array(
'meta_key' => 'std_roll',
'meta_value' => $roll,
);
$blogusers = get_users($args);
foreach ($blogusers as $user) {
echo '<li>' . $user->user_login . '</li>';
}
}
This is working in FF, Chrome completely. But in IE, error 404 not found error. Same in .NET (in HttpWebRequest), and android (HttpGet) also.
When I moved the code in WordPress theme ( a page template), everything was working fine.
What was the problem and how that can be fixed? | I was solved using
<?php
include_once('../wp-load.php'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "page template"
} |
Display posts of the last 7 days
I'm trying to display the 5 best rated posts of the last week (7 days) on my website, however I can't seem to figure out how to display them.
Here's what I've achieved so far but it doesn't seem to work:
<?php $slider_query = new WP_Query('posts_per_page=5&cat=3&orderby=highest_rated&order=desc'); ?>
<?php
$mylimit = 7 * 86400; //days * seconds per day
while ($slider_query->have_posts()) : $slider_query->the_post();
$post_age = date('U') - get_post_time('U');
if ($post_age < $mylimit) {
?>
//The Post
<?php } ?>
<?php endwhile;?> | In addition to birgire's solution, as of WordPress 3.7, you can use Date parameters.
Your arguments would look like this to filter posts from the last 7 days:
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
// Using the date_query to filter posts from last week
'date_query' => array(
array(
'after' => '1 week ago'
)
)
); | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 9,
"tags": "query posts, date"
} |
Create post thumbnails from images stored outside of uploads directory
I am redoing some of my older blogs and I noticed with the new themes most of them take advantage of featured images which is fine. The problem is a lot of my older posts that was never set either because I did not use it or because it didn't exist.
Now I know of the featured thumbnail plugin the regenerates your posts and it grabs the images from your post and makes a thumbnail which is great and that works, but I have some posts where the images were not stored in the uploads folder where the plugin seems to be looking and those posts fail.
Any thoughts on how I can get these featured images without going through every single post manually? | You need to first download those external images then you can attach and set them as the post thumbnail.
To download and attach you can use the `media_handle_sideload()` function.
I wrote a plugin that will search through all your posts and pages and download and attach any external image into the media library. It also has the option of setting the first image as the featured image.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, post thumbnails"
} |
get_term_link not working
I am trying to use the below code snippet to display an image and then wrap it in a link to a specific term archive page. In this case, I have a custom taxonomy (Series) with a few different terms. The variable $series outputs the Term Object, therefore I want to use the get_term_link function to get the URL to the terms archive page.
The documentation for get_term_link (< says that I should simply be able to provide the term object and it will work, but it's not. I'm getting a partial-page load, meaning the code is breaking when it reaches this function.
Any help is appreciated!
$imageid = get_sub_field('series_banner', 'options');
$image = wp_get_attachment_image( $imageid, 'home-series-banner');
$series = get_sub_field('series_link', 'options'); //Returns the term object ?>
<a href="<?php echo get_term_link($series); ?>"><?php echo $image; ?></a> | That field can return multiple term objects depending on how you've got it configured, so I'll guess that `$series` in this case is an array containing a single element, which contains your term object. Try inspecting the contents of series:
print_r( $series );
You'll probably see something like:
Array
(
[0] => stdClass Object
(
[term_id] => 1
[name] => test
[slug] => test
[term_group] => 0
[term_taxonomy_id] => 1
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
)
)
If this is the case, try passing `$series[0]` to `get_term_link`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
Character \ appearing before ' after saving a settings page
It's a strange issue and I've seen it happen with plugins, however I don't know how to fix it. Maybe just a PHP issue?
Anyhow, I have a settings/options page with several text areas. Upon saving, a "\" appears before each apostrophe. Each time it's saved, an additional back-slash appears.
I'm not sure what code would be helpful to look at for this. | It's a PHP issue. The character `'` is being escaped so that it can be safely in various places, not least of which is the database. That's why your `'` look like `\'`.
You can use PHP's `stripslashes()` function to clean it up, or (if it's an array you need to clean up) WordPress's `stripslashes_deep()` function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "options, text, esc textarea"
} |
Child Site doesn't appear in the Network menu
As you see in the snapshot, just the main site appear in My Sites menu, Although it appears correctly in the "Network Admin".
I used the subdomain installation when I configured the Wordpress MU. And this is the Wordpress MU part in wp-config.php
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'www.mydomain.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
!just the main site appearing | I found the solution , it's dead simple, I should add myself to the child site as a user, I guess this should be done by default. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, subdomains, domain mapping"
} |
Dont' charge customer until product ships - woocommerce
Is it possible to set woocommerce to not charge the customer until the product actually ships? | This is not so much a WooCommerce issue as a payment gateway issue. Paypal distinguishes, for example, between 'authorization' and 'capture', Worldpay has similar terms (and a different API).
E.g. for Paypal see
In the case of Paypal, check <
Authorization and Capture API operations: DoCapture Capture an authorized payment. DoAuthorization Authorize a payment. (Express Checkout only)
So you probably need at least the Paypal Express Gateway plugin: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins"
} |
Plugin fatal error
I'm trying to activate a plugin I made on a network site. I'm getting an error:
Plugin could not be activated because it triggered a fatal error.
I have the debug mode on and it outputs all errors into a debug.log, however nothing is given for this error.
Is there another way to see what the error may be?
The plugin registers a CPT with taxonomy. It was recently deactivated to test a few changes I made. Upon the reactivation it is failing. Something to note, the custom post type has 900 posts and 1400 taxonomy terms. Hopefully something comes to light without having to redo all that work for the posts. | I eventually muscled my way through it. The first thing I did was manually activated the plugin via the database. Next I went back to the subsite to verify that the plugin was activated. It was not.
So I tried activating again. Now I was getting an error in relation to memory being exhausted. This was caused from the large amount of data for my CPT and taxonomy.
I had to export my post and taxonomy tables from the database, then delete everything, before I was able to activate the plugin.
After the plugin was active, I was able to import the posts and taxonomy terms back into their respective tables. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, plugin development, custom taxonomy"
} |
Editing Category RSS Feeds
I have the following PHP code below that I would like to add to the category feed in WordPress.
<?php if(get_the_post_thumbnail()): ?>
<featured-item><?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?></featured-item>
<?php endif; ?>
I know that I can edit `feed-rss2.php` to add it into the general feed. But the same code isn't allowing me to add it to the category view of the same RSS feed.
Where do I place this code for the generated RSS feed? | FYI, you should _never_ hack the WordPress core files. Instead, WordPress provides the handy `rss2_item` action hook. All we need to do is check if we're on a category feed or not:
function wpse_99336_category_feed_item() {
if ( is_category() && get_the_post_thumbnail() ) {
printf ( '<featured-item>%s</featured-item>',
wp_get_attachment_url( get_post_thumbnail_id() )
);
}
}
add_action( 'rss2_item', 'wpse_99336_category_feed_item' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, rss, feed"
} |
WPDB Query Question with Category Only
I am trying to pull up posts from only category ID 18 with this query for a plugin I am working on but it will not work. I can not use `query_posts` or `WP_Query` in the place I am using this.
global $wpdb;
$posts = $wpdb->get_results( "SELECT ID, post_title, post_content, post_date
FROM $wpdb->posts
LEFT JOIN $wpdb->term_taxonomy
ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->term_taxonomy.term_id = 18
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND post_status = 'publish'
AND post_type = 'post'
ORDER BY post_date DESC
LIMIT 25" ); | This is a SQL problem. Your query is wrong. You forgot to include the term_relationships table in the query, yet reference it during the JOIN. By including the term_relationships table, that would solve the problem with the query.
SELECT ID, post_title, post_content, post_date
FROM {$wpdb->posts} AS p
JOIN {$wpdb->term_relationships} AS tr
ON tr.object_id = p.id
JOIN {$wpdb->term_taxonomy} AS tt
ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tt.term_id = 18
AND tt.taxonomy = 'category'
AND post_status = 'publish'
AND post_type = 'post'
ORDER BY post_date DESC
LIMIT 25 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wpdb"
} |
Handling duplicates with wp_insert_term()
I'm using `wp_insert_term` which works quite well
Now I want some error handler for when using the same name.
$term_id = wp_insert_term( $term, 'wpsc_product_category', $args );
if($term_id) {//my operations here}
where `$term = $_POST['categoryTitle'];`
I want to display some error when such name already exists.
In wp_insert_term, how to check if this `$term_id` is duplicate?
I don't want to continue my operations on already existing terms. | if ( is_wp_error($term_id) ) {
// oops WP_Error obj returned, so the term existed prior
// echo $term_id->get_error_message();
}
See if that works for you. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "errors, terms"
} |
How to generate "WP_Error" Object for user login?
I want to return the Login Error Message even user key-in their privileges correctly. In other words, to terminate the login and show the error message.
When we key-in wrong passwords, wordpress shows:
There was an error authenticating your details.
ERROR: The password you entered for the username admin is incorrect. Lost your password?
.. on the login page. This is because of `WP_Error` Object is returned.
So my curious question is:
* How to get/generate this `WP_Error` Object on my own, to return back? Is it Array? | > How to get/generate this WP_Error Object on my own, to return back?
$error = new WP_Error;
It is fairly well documented in the Codex.
Once you instantiate the object there are methods for adding errors and for retrieving them, and functions like `is_wp_error` to check a variable to see if it is an error object or not. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "login, authentication, wp error"
} |
Set conditional on template based on referring page slug
I have a portion of a page template that is conditional upon the following `elseif`
<?php elseif( isset( $wp_query->query_vars['details'] ) && $wp_query->query_vars['details'] == 'child':
Is there a way to exclude a queries from a particular page slug? I would like to exclude queries coming from a page called `services-we-provide`.
I tried the following with no luck:
&& !$wp_query->query_vars('pagename=services-we-provide')
**EDIT:** I guess another thing I could do is add a `elseif` before the one above that looks to see if you're coming from the services-we-provide page...is that possible, if so, how would I go about that?
**EDIT 2:** A little more research and I foudn that this is usually done with a referrer. I found this javascript, however I'm unclear how / where to implement and how to reference in the `elseif` statement: <
Any help would be greatly appreciated. | I ended using the `wp-get-referer` function in a conditional. Here's the resulting code:
<?php
$ref1 = parse_url(wp_get_referer()); //getting the referring URL
if($ref1["path"]=='/services-we-provide/')
:?>
//Do stuff
<?php else: ?>
//Do other stuff
<?php endif ;?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, query, conditional tags"
} |
How to backup and restore configurations
I am in the process of transferring my WordPress blog to a new host. I've copied the blog files, used XML import/export to copy the contents, and the blog is now up and running.
The missing piece is configuration. At the new blog, all the plugins are turned off, the widget are set to default and the plugin settings (e.g. Google Analytics code) are not set.
**How do I transfer my configuration and plugin settings from my old blog?** | You must export all table beginning with your WordPress prefix.
1. Open your phpmyadmin panel.
2. Then open your wordpress database.
3. Click "export" from top menu.
4. Select "Export Method:" as custom.
5. Select your all tables beginning your prefix.
6. Then go to bottom of page click "go".
You got your SQL file. Move all files to new directory. If you create a new database on new host, you must change the database name on wp-config.php.
* Then you must import your SQL file to new database.
* Replace the old domain name with the new domain name. Go to wp_options table on your database.
* Change siteurl option name. on second page change "home" option name with new url. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "backup, configuration"
} |
How to update/delete array in post meta value?
I using post meta like..
$meta = get_post_meta(99,'_mymeta',true);
$value = $meta['somekey'];
echo $value;
But how to update `$meta['somekey']` to some another value ?
How to use update_post_meta to update sub meta key ?(Idk, How ppl call)
update_post_meta(99, '_mymeta["somekey"]', 'myAnotherValue');
????? | To update post meta that are an array: you have to fetch the original values, change the value you need and update it again. For example
$list_of_values = get_post_meta($post_id, '_list_values', true);
if(!empty($list_of_values)) {
$list_of_values["some_prop"] = "new value";
}
update_post_meta($post_id, '_list_values', $list_of_values); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "post meta"
} |
wp_insert_post not updating custom taxonomy selected if logged in as a subscriber
Here is my Code, it works fine When i try to post data from front end if Logged in as admin, but if i logged in as a subscriber code works fine but it is not inserting the taxonomy term i select, here is the code..
$new_post = array(
'post_title' => $postTitle,
'post_content' => $post,
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'publications',
'tax_input' => array( 'publicationstype'=> $term_id )
//'post_category' => array(6)
);
wp_insert_post($new_post);
here 'publicationstype' is the custom taxonomy, is there any one, who can help me!! thanx in advance | It's because within `wp_insert_post` current user capabilities are checked before adding the terms:
if ( current_user_can($taxonomy_obj->cap->assign_terms) )
wp_set_post_terms( $post_ID, $tags, $taxonomy );
to get around this, use `wp_set_object_terms` instead after `wp_insert_post` to add the terms:
$new_post = array(
'post_title' => $postTitle,
'post_content' => $post,
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'publications'
);
$new_id = wp_insert_post( $new_post );
wp_set_object_terms( $new_id, $term_id, 'publicationstype' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom taxonomy, taxonomy, wp insert post"
} |
why does bones theme call the_excerpt function with parameters?
I have been triying to localize a wordpress site which uses Bones as the theme.
In the theme's search.php, there is a line that goes:
<?php the_excerpt('<span class="read-more">' . __('Read more »', 'bonestheme') . '</span>'); ?>
In the function reference it is said that this function does not take any parameters. So why does this theme send parameters? | This is a bug in the theme. The real function does indeed not use the parameter:
/**
* Display the post excerpt.
*
* @since 0.71
* @uses apply_filters() Calls 'the_excerpt' hook on post excerpt.
*/
function the_excerpt() {
echo apply_filters('the_excerpt', get_the_excerpt());
}
PHP will just ignore it, but the unnecessary gettext call should be avoided. Write a bug report. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, search"
} |
Add a custom stylesheet for BlackBerry
I want a little help loading a custom stylesheet in wordpress. I'm using PHP to check if the user agent is BlackBerry. If yes, I want to load blackberry.css, if no, regular wordpress style.css.
Here's what I have so far:
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
$pos_blackberry = strrpos($ua, "blackberry");
$pos_webkit = strrpos($ua, "webkit");
if (!($pos_blackberry === false)) {
if (!($pos_webkit === false)) {
**//load blackberry.css**
}
} else {
wp_enqueue_style( 'twentytwelve-style', get_stylesheet_uri() );
}
**Question:** what is the "grammatically correct" WordPress syntax for loading blackberry.css stylesheet? | Well... You've already used `wp_enqueue_style`. Use it again. That is the canonical mechanism for loading stylesheets either by itself or in combination with `wp_register_style`
wp_enqueue_style('blackberry',get_stylesheet_directory_uri().'/path/to/blackberry.css');
I feel compelled to note that user agent sniffing is not especially reliable. Is it not possible to do this with media queries?
## Reference
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, css"
} |
Switch Categories on a Specific Date?
I usually like to provide a code I've started with and have others help me out with it - but this is one where I don't even know where to begin.
I would like to be able to set a date on posts in which the selected post will automatically be moved to another category. Has anybody attempted this? | I don't know if this can be accomplished with WP alone.
I would create two custom fields for your posts.
1. First custom field would hold the date you want make the switch
2. Second field would hold the category you want the post to switch to
(Assuming it's not always the same post and not always the same category)
Then I would write a cron-job (that runs daily) to run a php script with a SQL statement to check your database and make the necessary updates. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "date"
} |
Navigation menus not showing because of custom post type filter
I use this filter to show content from all custom post types in tags archive page
function tagFilter($query) {
$post_type = $_GET['type'];
if (is_tag()){
if (!$post_type) {
$post_type = 'any';
}
$query->set('post_type', $post_type);
}
return $query;
};
add_filter('pre_get_posts','tagFilter');
but somehow it stops the `wp_nav_menu` function and navigation menus do not appear in tags archive pages. I can't figure out where is the conflict between the two.
Any ideas? | This:
if (is_tag()){
will be true for _any query_ on a tag archive page, including the query WordPress makes to load menu items.
You want to check if the _current query_ is both the main query and tag query:
if ($query->is_main_query() && $query->is_tag()){ | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "custom post types, menus, tags, archive template"
} |
is_plugin_active() returning false on active plugin
So I have the following in an include in my theme file:
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( WP_PLUGIN_DIR . '/woocommerce/woocommerce.php' ) ) {
$shop_id = woocommerce_get_page_id( 'shop' );
$shop_page = get_page( $shop_id );
}
but `is_plugin_active( WP_PLUGIN_DIR . '/woocommerce/woocommerce.php')` is returning false, despite the fact that the plugin is active.
I'm wondering if `is_plugin_active()` might be tripped up by the theme customizer, because the fact that I'm doing this while hooked to `customize_preview_init` is the only gotcha that I can imagine would be causing issue. Any insights? | `is_plugin_active()` expects just the base name of the plugin as parameter:
So use:
is_plugin_active( 'woocommerce/woocommerce.php' );
The function will use the option `'active_plugins'` which is a list of plugins paths relative to the plugin directory already.
On a multi-site installation it will search in `get_site_option( 'active_sitewide_plugins')` too.
As an implementation note: Avoid these checks. Some users rename plugin names or directories. Test for the functions you will actually use instead, eg:
if ( function_exists( 'woocommerce_get_page_id' ) )
{
// do something
} | stackexchange-wordpress | {
"answer_score": 26,
"question_score": 9,
"tags": "plugins, include"
} |
Wordpress User Name Limitations
I need to know what the wp specifications for the usernames are. Like allowed minimum and maximum length, are special characters like ü,ö,ä,ß accepted,..?
Unfortunately I couldn't find any insight on this in the interweb. Do you have any? | I think the answer is in the source.
$username = wp_strip_all_tags( $username );
$username = remove_accents( $username );
// Kill octets
$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
$username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
// If strict, reduce to ASCII for max portability.
if ( $strict )
$username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
So, the code strips tags, octets, and html entities. And it replaces accented characters with unaccented ones via the `remove_accents` function, which is fairly lengthy. Other characters get through unless `$strict` is `true` (default is `false`), in which case only ASCII characters are allowed.
The maximum login name length would be the database limit for the user_login column\-- 60 characters. The minimum, as best I can tell, is 1. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "limit, username"
} |
Display all comments or recent comments per user on author page
I have author pages for each author and I want to see all of their comments (or all of their recent comments) if I click on their nickname. How can I do this? I tried the beneath code, but that does not show the unique comments per user... It just outputs all recent comments from everyone combined, but I don't want that.
<?php
$author_email = get_the_author_meta( 'user_email' );
$args = array(
'author_email' => $author_email,
'number' => '10'
);
$comments = get_comments($args);
foreach($comments as $comment) :
echo('<li class="comment">' . $somment->comment_content),'<h5><a href='.get_permalink($comment->comment_post_ID).'>', get_the_title($comment->comment_post_ID), '</a></h5>', '<time><em>' . $comment->get_comment_date . '</em></time>', '</li>';
endforeach;
?>
</ul></div> | your problem is using `author_email`, you need `user_id`:
i just use similar script.
<?php
$args = array(
'user_id' => get_the_author_meta('ID'),
'number' => 10, // how many comments to retrieve
'status' => 'approve'
);
$comments = get_comments( $args );
if ( $comments )
{
$output.= "<ul>\n";
foreach ( $comments as $c )
{
$output.= '<li>';
$output.= '<a href="'.get_comment_link( $c->comment_ID ).'">';
$output.= get_the_title($c->comment_post_ID);
$output.= '</a>, Posted on: '. mysql2date('m/d/Y', $c->comment_date, $translate);
$output.= "</li>\n";
}
$output.= '</ul>';
echo $output;
} else { echo "No comments made";}
?> | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "comments, author, author template, recent posts"
} |
Update permalinks after domain change
I installed my blog in a free hosting webpage, the hosting gave me a free domain and I used that domain in my blog, then I did buy a .net domain, I changed the URL in Settings->General of my dashboard.
I usually edit old posts, the problem is when a reader enters in the blog with the old free domain he gets the old version of my post, when the reader enters with my .net post he gets the modified version
I tried fixing the problem renaming all the link in my database, but it didn't work.
How can I fix this? | Option A: Here’s a Quick Way to Search and Replace Your WordPress Database
Option B: Export your database using phpmyadmin and open in a text editor such as (Notepad++), and use search/replace to find old domain and replace with new domain. **MAKE SURE YOU BACKUP YOUR DATABASE BEFORE TAKING ANY ACTION** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, urls"
} |
Show image exactly defined to a width
I have a photoblog displaying posts as image galleries having width 500px and some posts as single image of width 900px. For posts with 900px width images, I made `category HQ`.
Posts with 500px width image galleries display fine. But those posts having single image doesn't display image of width 900px width instead 584px. E.g. Post content for 900px width image:
<img class="alignnone size-full wp-image-15735" alt="Camping in the Rocky Mountains " src=" width="900" height="700" />
Getting image info in browser shows 584px width. On further inspection, I came to know that there is a `$content_width variable` in `functions.php` set to 584px. I can't change it as I read it is for oEmbeds.
How to get this 900px width image to show as 900px width? | If `$content_width` is the problem, you could set it to something different if you're viewing a single HQ post.
function wpse99587_single_hq_post() {
global $post;
if( is_single() && in_category( 'HQ', $post->ID ) ){
global $content_width;
$content_width = 900;
}
}
add_action( 'wp', 'wpse99587_single_hq_post' );
// I dithered on where to hook this function;
// if there's a better hook to use, please correct me
This assumes that the `$content_width` variable is global.
See the Codex pages for `is_single()` & `in_category()` for more information. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, post content"
} |
Use oEmbed in List Items
I'm aware that WordPress has oEmbed functionality. But the content to be embedded has to be on it's own line like so:
Lorem Ipsum
More Lorem Ipsum
Unfortunately, my markup looks like this so oEmbed doesn't work and I have to use a plugin.
<ul>
<li>
<li>
</ul>
Is there anyway I can get oEmbed to work without this plugin? A line or two in functions.php would be better than this plugin. | Just use the `[embed]` shortcode around your items.
<ul>
<li>[embed]
... | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, youtube, oembed"
} |
What does setup_postdata ($post ) do?
The codex defines it as 'Set up global post data. Helps to format custom query results for using Template tags.' I don't really understand this.
Here is a code example :
global $post;
$args = array( 'numberposts' => -1);
$posts = get_posts($args);
foreach( $posts as $post) : setup_postdata($post);
echo $post->ID;
endforeach;
Please can you explain? | Template tag functions rely on global variables to access the post being processed and retrieve data from it or related to it.
The main variable among these is `$post`, which holds the post object itself.
In your example it's not explicit, but what is happening is that your loop assigns data to `$post`. If its name wasn't `$post`, you would need to name it explicitly (`global $post; $post = $some_other_post;`).
However, there are a bunch of other globals and the purpose of `setup_postdata()` is to fill them with data. If you look at the source, these are:
global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
Note that in most cases you should be calling `wp_reset_postdata()` afterwards to return globals to their original state. | stackexchange-wordpress | {
"answer_score": 21,
"question_score": 19,
"tags": "get posts"
} |
What does extract( shortcode_atts( array( do?
The codex says
> _**`shortcode_atts()`** combines user shortcode attributes with known attributes and fills in defaults when needed. The result will contain every key from the known attributes, merged with values from shortcode attributes._
It doesn't make much sense to me (I'm a newbie).
Here is an example:
function wps_trend($atts) {
extract( shortcode_atts( array(
'w' => '500',
'h' => '330',
'q' => '',
'geo' => 'US',
), $atts));
$h = (int) $h;
$w = (int) $w;
$q = esc_attr($geo);
ob_start();
Please can you explain? | `shortcode_atts()` works like `array_merge()`: It merges the second list of arguments into the first one. The difference is: It merges only keys present in the first argument (`$default`).
`extract()` then takes the array keys, sets these as variable names and their values as variable values. `'w' => '500'` in your example becomes `$w = '500'`.
Do not use `extract()`. This very bad code style. Its usage was deprecated even in core, and that means something … :)
Your example should be written as:
$args = shortcode_atts(
array(
'w' => '500',
'h' => '330',
'q' => '',
'geo' => 'US',
),
$atts
);
$w = (int) $args['w'];
$h = (int) $args['h'];
$q = esc_attr( $args['q'] ); | stackexchange-wordpress | {
"answer_score": 44,
"question_score": 34,
"tags": "shortcode"
} |
What does get_current_screen() do?
Codex says ' This function returns an object that includes the screen’s ID, base, post type, and taxonomy, among other data points' . What does it mean by 'screen'?
Coding example:
function change_default_title( $title ) {
$screen = get_current_screen();
if ( 'POST_TYPE' == $screen->post_type ) {
$title = 'Enter Invoice Title';
}
return $title;
} | If you look at the source of `get_current_screen()` it's a really small function the merely gives you value of `$current_screen` global variable. There is matching `set_current_screen()` that fills that variable.
What the variable actually contains is instance of `WP_Screen` class. There is plenty going on in that class, but in a nutshell it keeps track of context for admin page you are currently seeing and implements functionality, shared between admin pages. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post type"
} |
How to make a website like the ones in theme demos?
I don't understand, in Joomla there was a quickstart package that came with templates to show the template's power with data. So our site would be like the one we see in the demos.
I have found some nice themes in WordPress, how can I make my site like the one I see in these demos?
* <
* <
* < | Theme demos, especially commercial ones, do not display out-of-the-box state of it. They are hand crafted and fine-tuned setups designed to sell (or at least convince for free ones).
The official set of content that is typically used for quickly reviewing, evaluating and testing theme is called Theme Unit Test data.
There are also unofficial sets, such as WP Test.
Note that parts (sometimes most) of what you are seeing might be completely custom functionality, specific to that theme. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": -1,
"tags": "themes, content"
} |
Advanced custom field - gallery - display one random image
I created a gallery with the "gallery add-on" of "advanced custom field" plugin.
I'm trying to show one random image from the gallery on page refresh. Here's my code:
<?php
$gallery = get_field('gallery_home');
$rand = array_rand($gallery, 1);
if( $rand ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?>
But the result is this:
<img src="" alt="">
Where am I missing something? | Shouldn't you be doing something like this?
<img src="<?php echo $rand['url']; ?>" alt="<?php echo $rand['alt']; ?>" />
**Update**
I'm not really familiar with that plugin (stuff could be happening behind the scenes) but here's a better guess than my previous one:
<?php
$gallery = get_field('gallery_home');
$rand = array_rand($gallery, 1);
if( $gallery ): ?>
<img src="<?php echo $gallery[$rand]['url']; ?>" alt="<?php echo $gallery[$rand]['alt']; ?>" />
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "advanced custom fields"
} |
Pull Instagram images into an existing loop?
I am looking for a solution to pull Instagram images (from a single account) into a Wordpress loop and mix them chronologically with standard posts that will have been created within the Wordpress admin.
So the archive page would be a mix of news items (full posts) and Instagram images, all in the same feed, appearing chronologically from whenever they were posted.
Is that possible (with or without a plugin)?
Thanks in advance for your response! | I found that I was able to do this by using the Instagrate Pro plugin, which creates individual posts for every image it pulls in from Instagram. The standard loop then just pulls in those posts into the archive. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, loop, images"
} |
How to set hierarchical terms to a post using wp_set_object_terms
I have a hierarchical custom taxonomy called "locations". The parent categories are country names, the child categories are the territories under the country.
How can i attach these terms to a post programatically?
$country = 'Egypt';
$territory = 'Hurghada';
So, if the Egypt category doesn't exist, i need to create it, and i need to attach the $territory in a subcategory under Egypt.
This is where i am so far:
$post_id = 10;
$country_term_id = term_exists( $country, 'locations' );
if ($country_term_id !== 0 && $country_term_id !== null) {
wp_set_post_terms($id, $country,'locations');
} else {
//I guess this is where i need to set the territory?
} | Since `wp_set_post_terms()` does not accept hierarchy for it, you will first have to check if terms exist already, create them using `wp_insert_term()` if not and only then assign to post.
Note that there had been (don't know current state) some cache related bugs with doing such things on the fly, see Inserting terms in an Hierarchical Taxonomy | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, taxonomy, hierarchical, terms"
} |
How can I highlight specific pieces of text within a blog post?
I have searched for a simple method to allow a user to highlight a specific piece of text with a user chosen color but have not found one readily apparent. I have found a few methods related to syntax / code highlighting. I am not trying to highlight code but merely text within a blog post. Preferably I would like a simple method that provides a UI button within the editor itself as some users that post articles are not technically savvy and may have issues with short codes. I am currently running Wordpress version 3.5.1. | While I rarely recommend plugins, the CKEditor plugin will do highlighting of selected text. That sounds like exactly what you want. And it is a greatly enhanced editor relative to the default one. Short of creating your own editor buttons and supporting functions, that would be a pretty good choice. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "text, plugin syntaxhighlighter"
} |
Echo author slug in post edit page
On the Post edit page in the back-end, how do I echo the author's `user_nicename`? I am referring to the author of the post, not current user. | Found it:
global $post;
$author_id=$post->post_author;
the_author_meta('user_nicename', $author_id ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "posts, php, author, slug"
} |
Wordpress <!--more--> adding a <br> to my anchor for Read More
When creating a post within my wordpress site (using the editor) I want to add the short code, or even use the link at the top of the editor to do so.
The end result is (it does create the excerpt and add the "Read more" link) but that link is broken and the editor has seemingly inserted a
tag within my anchor breaking the link.
`<a href=" /> /a-test-post/" class="more-link">Read more »</a>`
Anyone have an idea as to why this would be happening? | Because of the way that `wpautop` works, I would expect that if you had a newline, or or maybe a space in your URL. I can't seem to get a space or newline to save from the admin interface, but it is trivial to insert by editing the `WP_HOME` and `WP_SITEURL` constants into `wp-config.php`... but that causes every page to 404 or worse.
There must be something happening when the link is generated-- possibly something hooked to `excerpt_more` or `the_content_more_link`. It is also possible that your theme is parsing the more link itself and bypassing the normal channels.
Without more information, that is all I have.
## Reference
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "read more, html editor"
} |
How to Put Custom Taxanomy Meta Box in Main Column
WordPress added the Custom Taxonomy Meta box at sidebar, Is there any way which we can relocate it in the main column , Under Edit box?
Thansk | Unfortunately WP is hardcoded to generate taxonomy metaboxes in that `side` location.
It is tad fragile, but possible to throw generated data around from one location to another:
add_action( 'add_meta_boxes', 'move_taxonomy_metabox' );
function move_taxonomy_metabox() {
global $wp_meta_boxes;
$taxonomy = 'test';
$metabox_key = 'tagsdiv-' . $taxonomy; // or $taxonomy . 'div' if hierarhical
if ( isset( $wp_meta_boxes['post']['side']['core'][$metabox_key] ) ) {
$metabox = $wp_meta_boxes['post']['side']['core'][$metabox_key];
unset( $wp_meta_boxes['post']['side']['core'][$metabox_key] );
$wp_meta_boxes['post']['normal']['core'][$metabox_key] = $metabox;
}
}
More proper way might be to just nuke generated metabox and completely redo registration. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom taxonomy, metabox"
} |
Unable to get WordPress auto update working on Ubuntu 12.04
I'm getting a tiny bit fed up with having to `chown 777` my entire WordPress folder in order to auto update a plugin, and then set the permissions back again. I've looked around for fixes now, but no fix I try seems to work.
I'm on an Amazon EC2 instance running Ubuntu 12.04. So, the Apache2 installation is stock standard out of the box, runs as the www-data user.
I've set my owner:groups to my entire project to ubuntu:www-data, and the permissions through the bank is set to `***rwxrwx--r**`, or `774`, meaning that either the ubuntu user, or the www-data group will have full read/write access to the file structure.
Whenever I try to update WordPress however, it asks me for FTP/SFTP details, so in order to get that going away, I need to run `chown -R 777` ... on the entire project folder.
That's annoying, and I've got no clue as to why this is happening. How can WordPress execute something other than the Apache2 user? | Found a fix. Simply add the following snippet to functions.php for your theme:
if(is_admin()) {
add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
define( 'FS_CHMOD_DIR', 0751 );
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "automatic updates"
} |
the_meta - no get_the_meta query?
I want to use `the_meta` as though it were `get_the_meta`. I want to do this because when i use `the_meta` in my `functions.php` file (I'm using a shortcode to enter data to pages), it posts the meta information to the top of the post as opposed to where I want it.
I have tried `get_the_meta`, but it doesn't seem to work and instead, it returns an error because it's obviously not a valid query. | You are getting an error because `get_the_meta` isn't a function. Just because many `the_*` functions have a corresponding `get_the_*` function, it doesn't mean that all do.
What you want is `get_post_meta` or `get_post_custom`. Those will return arrays which you will have to loop over and format yourself. `the_meta` uses `get_post_custom`. You can use its code as a template for your own code if you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, custom field"
} |
How to add custom page using them in wordpress 3.5
I did this before in wordpress 3.4 but that code seems not working. I add this code inside `wp-content/themes/` folder and I add new page from backend and try to select that. But it is not showing up, it's because new version..or am I doing it wrong?
<?php
/*
Template Name: Cover_Page
*/
?>
<?php get_header(); ?>
Here's my cover page!
<?php get_footer(); ?> | Hm, first of all your page template has to be inside your **current** theme folder: `/wp-content/themes/current-theme/` or in a similar folder. Check the Codex (Page Templates #File Folders) to make sure your template is in the right folder.
While looking at the Codex also check the Selecting a Page Template section above if you did everything the right way. Your page templates are **only** visible for pages, so you'll not find them in the post section or somewhere else. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -2,
"tags": "customization, themes"
} |
Get categories without post
I want to get categories that had NO post. Below is sql for getting category with post..
SELECT terms.term_id,terms.name,COUNT(post.ID) FROM wp_posts as post
JOIN wp_term_relationships as rel ON post.ID = rel.object_ID
JOIN wp_term_taxonomy as ttax ON rel.term_taxonomy_id = ttax.term_taxonomy_id
JOIN wp_terms as terms ON ttax.term_id = terms.term_id
WHERE ( ttax.taxonomy='category' AND post.post_type='post' AND post.post_status != 'revision') GROUP BY (terms.term_id)
But how to get catgeory with NO post? Thank you for your help. | **Here is how you can list the empty cat's**
this way can also refrence each category data like ID, Name etc
$args = array(
'hide_empty' => 0,
'pad_counts' => true
);
$categories = get_categories( $args );
foreach($categories as $category) {
if($category->count == 0) {
echo $category->name."<br />";
} else {
// do nothing
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "categories"
} |
WooCommerce Cart not showing up
I have just installed the WooCommerce plugin on my existing Wordpress theme. I have integrated the plugin using the correct functions as found in the WooCommerce integration guide.
Now the shop index works fine, as does the product page. However, when I click 'add to cart', and then 'view cart', the shopping cart page is completely blank.
I am not sure what this is, as the cart page (generated by the plugin) has the correct WooCommerce shortcode:
[woocommerce_cart]
I also increased the memory on my server as I read somehwhere this could have been a restriction.
I am not sure what else to do, any ideas? | I found the problem. The page.php in my theme was only calling the header and footer php files. It was not calling the the_content, I added this function and it solved the problem. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -2,
"tags": "plugins"
} |
Replace post/page titles with an image in Wordpress
I have a Wordpress theme bought from a well known site. I'm trying to change the location of the main site logo to where the page/post titles appear.
The page.php for the title is as follows;
How would I add an image to this?
<div class="clear headtop" style="height: auto;">
<div class="page-title" style="width: 100%; margin-bottom: 40px;">
<h1 class="vfont"><?php the_title(); ?></h1>
</div>
</div>
the site url is <
Thanks for your help
Gary | I would actually handle this with CSS. In your `style.css` file add something like this:
.page-title h1 {
text-indent: -9999px;
background: url(images/your_logo.png) 10px 10px no-repeat;
height: 100%;
}
You'll then make sure that your logo is added to your theme's `images` folder. Also, adjust the size of the image accordingly, or you can also adjust the size of the container.
Notice the two `10px` values. That's your top / left offset (I just picked a couple values to show you those). Adjust those to your liking.
Hope that helps a bit, have fun! | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "images"
} |
Modify custom field from front end
If I need to manage a custom field under wordpress, but not from the admin area. In other words, I need that users modify the content of post custom fields from front end. What is the way to do so?
As instance, please to imagine Stackexchange.com as a wordpress site. Under this site, the the accept state is my post custom field. How can I make the front end user modify its value in WP database?
Please If you have another better approach to create accept system, using wordpress, it will be highly appreciated. But if my approach (using post custom field) is okey, please to guide me find documentation from web or codex to achieve my goal.
Thank you for your usual help. | I assume that you want to update custom field.
You can use:
global $post;
update_post_meta($post->ID, $meta_key, $meta_value);
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, post meta, front end"
} |
Should i delete the posts created by a plugin on uninstall?
I created a plugin which is based on a Custom Post Type. When someone uninstalls this plugin, should i delete the posts under this post type or i should just leave them untouched? | This question is borderline "not constructive", because it's going to solicit opinion rather than objective fact or expertise.
That said: my _opinion_ is:
1. By default the Plugin should not touch user-generated content
2. It would be considerate to offer a "delete content" checkbox option at uninstall | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, custom post types"
} |
Post title not output correctly
I am trying to set up titles of posts with WordPress SEO, however my title gets output like this:
My post name
There is no separator and site name.
Here's the code in the theme:
<title><?php wp_title(''); ?></title>
In the WordPress SEO settings, under Post Types > Posts I have the following setting for titles:
%%title%% %%page%% %%sep%% %%sitename%% | From the WordPress SEO FAQ:
... either enable "Force rewrite titles" on the SEO -> Titles settings page, or go into your header.php and change the title element to just this:
<title><?php wp_title(''); ?></title>
Did you try that? | stackexchange-wordpress | {
"answer_score": 5,
"question_score": -3,
"tags": "seo"
} |
How to add GET variable after script url?
So, I've registered and enqueued my script.
`
But how do I add a GET variable on the script src url?
`
Any help appreciated. | Filter `script_loader_src` and use `add_query_arg()`. You can use `parse_url()` or the second argument `$handle` to target specific scripts...
I have included multiple redundant options here:
add_filter( 'script_loader_src', 'wpse_99842_add_get_var_to_url', 10, 2 );
function wpse_99842_add_get_var_to_url( $url, $handle )
{
if ( 'my_handle' !== $handle )
return $url;
if ( empty ( $_GET['myvar'] ) )
return $url;
$parts = parse_url( $url );
// specific host
if ( 'example.com' !== $parts['host'] )
return $url;
// specific path
if ( '/foo/bar' !== $parts['path'] )
return $url;
// or specific start of path
if ( 0 !== strpos( $parts['path'], '/foo/' ) )
return $url;
return add_query_arg( 'myVar', $_GET['myvar'], $url );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "scripts, wp register script"
} |
Display CPT index page as front/home page
I'm building a website that's sole purpose is to display other websites (defined in the CPT). Think of it as a portfolio site for a company's digital assets. I have already defined the CPT and added websites to it. I created a `portfolio-archive.php` template (the CPT's name). Which is now accessed at the `/portfolio` slug. I want this to be the homepage of the site. How would I go about doing that? | Rename `portfolio-archive.php` to `front-page.php` and change the post type for that page with a filter on `pre_get_posts`:
add_filter( 'pre_get_posts', 'wpse_99860_portfolio_on_front' );
function wpse_99860_portfolio_on_front( $query )
{
// not the main loop
if ( ! $query->is_main_query() )
return $query;
// not the front page
if ( ! $query->is_front_page() )
return $query;
$query->set( 'post_type', array ( 'portfolio' ) );
return $query;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, archives"
} |
first instantiated SimplePie object cosumes 5mb?
This following lines causes 5mb memory consumption. It appears large to me.
if ( ! class_exists( 'SimplePie' ) ) include_once( ABSPATH . WPINC . '/class-feed.php' );
new SimplePie();
I'm using php 5.2.4, WordPress 3.5.1.
With PHP 5.4.3, the memory usage with the above lines becomes 2.25mb.
I'd like to know a way to reduce it if there is a workaround. | This is a known issue. It is caused by a bug in PHP 5.2 and is fixed in PHP 5.3.
You need to manually call the destructor method before unsetting the $feed and $item variables.
source | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.