INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to have "the most used tags" taxonomy always expanded?
How can I have some taxonomies to always have "the most used tags" displayed when a new post is being created.
Thanks. | There does not appear to be any way to hook into that from inside PHP
<
So JavaScript will probably best suit as a quick and easy solution.
add_action( 'admin_footer-post-new.php', 'wpse_45149_inject_script' );
function wpse_45149_inject_script() {
$expand_for = array( 'post_tag' ); // add taxonomy names here
// build a nice jQuery query
foreach ( $expand_for as &$tax_name ) $tax_name = '#link-'.$tax_name;
$expand_for = implode( ',', $expand_for );
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('<?php echo $expand_for; ?>').click();
})
</script>
<?php
}
You should probably `wp_enqueue_script` this script instead (always set position to "footer"). And also hook to the `edit.php` pages if necessary. Moreover, `$expanded_for` should probably be escaped. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "taxonomy, tags"
} |
How to grab data (titles, thumbnails and custom fields) from multiple posts to populate a new array efficiently?
I need to know the most efficient method to grab 3 pieces of data from from multiple posts:
* Post title
* Thumbnail
* Custom Field
I am attempting to build a Google map of posts using data stored in WP posts. Each post has geo coordinates and a thumbnail. I want to pull the title, geo custom field and thumbnail and use this data to build points of interest on a map. The posts are stored as a custom post type called listings.
Here is a demo: <
Here is my query code:
$args=array( 'showposts' => 45 );
query_posts( $args );
Currently this is failing to query anymore than 45 posts. I have over 400 listings that I would like to query. Not sure why it's failing. | Sorry! Turns out the problem with query_posts failing here was due to my PHP memory_limit. I changed it from 8mb to 128mb and the problem goes away. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom field, query posts, query, google maps"
} |
Multisite Pull Recent Image Attachments from Blog ID
I am creating a WordPress network and am looking for a way to pull recent images from the sub blogs, but I am having some trouble doing so.
What is the easiest way to make this happen? | Use `switch_to_blog` to switch blog contexts to a specific blog ID. From there on it's all down to `get_posts` of the `attachment` type. And switching back to the current context with `restore_current_blog`.
Something like this:
switch_to_blog( $blog_id );
$args = array( 'post_type' => 'attachment', 'numberposts' => 5, 'orderby' => 'post_date', 'order'=> 'ASC' );
foreach ( get_posts( $args ) as $attachment ) {
echo wp_get_attachment_image( $attachment->ID );
}
restore_current_blog(); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, images, blog id"
} |
Prevent access to single post types
Say that I want to make a post type called 'press' and it is mostly concerned with linking a title with a PDF document of a press clipping. I want to show all of these as an archive... so something like site.com/press but i don't want any single post template pages. so no site.com/press/article1 or site.com/press/article2. other than not including a link in my archive template (which just obscures it but doesn't negate their existence or prevent access to the single posts) how can i prevent a visitor from inadvertently accessing the single posts. how could i re-direct them back to the /press archive? | ## The fast way
In your .htaccess add a rule
RedirectMatch Permanent ^/press/.+ /press/
## Plugin way
Hook into `template_redirect` and redirect all requests to a single entry:
add_action( 'template_redirect', 'wpse_45164_redirect_press' );
function wpse_45164_redirect_press()
{
if ( ! is_singular( 'press' ) )
return;
wp_redirect( get_post_type_archive_link( 'press' ), 301 );
exit;
}
_(Caveat: not tested)_ | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 6,
"tags": "redirect"
} |
Generate multiple tag query URLs
As we know WordPress supports multiple tag queries (',' and '+'). The only problem with this `add_query_arg()` doesn't handle these methods if a query param is already exists in the URL.
From the following url `www.domain.com?post_type=ptype¶m=value1 add_query_arg('param', 'value2')` will generate `www.domain.com?post_type=ptype¶m=value2` insead of `www.domain.com?post_type=ptype¶m=value1,value2` or `value1+value2`
I would only use comma separated (OR) method. Could you please help me to write a function which adds additional param value next to an exsisting one? regular expressions perhaps? | $url = parse_url( $your_url );
$query = $url['query'];
$args_arr = array();
parse_str( $query, $args_arr );
if( isset( $args_arr['param'] ) ) {
$query_string = $args_arr['param'];
$query_string .= ',value2';
} else {
$query_string = 'value2';
}
add_query_arg( 'param', $query_string );
That's completely untested, but you get the concept. Basically, wordpress is gonna want to replace what you have set in `param`, so you need to get what you have in param, then add what you want to add to it. You can definitely make that into a function if you want to, depends on your usage case. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, multi taxonomy query, advanced taxonomy queries"
} |
Form validation on user profile edit
I have added a custom field to user profiles in bbPress however I am unsure how to do form validation other than javascript. I would like to do some PHP validation however the few things I have tried didn't work.
If you fail to enter an email it will say "ERROR: Please enter an e-mail address." after you have submitted the form. I want something like that.
I have tried:
$myErrors = new WP_Error();
$myErrors->add('id_error', __('Test error.',""));
bbp_add_error( 'bbp_steamid_invalid', __( '<strong>ERROR</strong>: The ID you entered is invalid.', 'bbpress' ) );
I am not at all familiar with error handling in both WordPress and bbPress however I feel it is a must.
Any help would be must appreciated. | I worked it out.
add_action( 'user_profile_update_errors', 'validate_steamid_field' );
function validate_steamid_field(&$errors, $update = null, &$user = null)
{
if (!preg_match("/^STEAM_[0-5]:[01]:\d+$/", $_POST['_bbp_steamid']))
{
$errors->add('empty_steamid', "<strong>ERROR</strong>: Please Enter a valid SteamID");
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "forms, bbpress, validation, errors"
} |
Return all custom meta data for one custom post type
I've set up a custom post type which has three custom meta fields: name, latitude, longitude. Each post already shows the name on an integrated map based on it's latitude and longitude.
I now would like to add a page to my site which shows ALL the names on a map based on their latitude and longitude.
I obviously know how to get single values out and get them on a map, but I'm not that experienced in Wordpress so I'm not sure what the best way would be to get all this information out in a structured way for what I'm trying to do. Any pointers to get me started would be appreciated. | If all of your custom post type posts have all meta fields that you need then you can use the `fields` argument and set it to `ids` which will work much faster for example:
//get your custom posts ids as an array
$posts = get_posts(array(
'post_type' => 'your_post_type',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids'
)
);
//loop over each post
foreach($posts as $p){
//get the meta you need form each post
$long = get_post_meta($p,"longitude-key",true);
$lati = get_post_meta($p,"latitude-key",true);
$name = get_post_meta($p,"name-key",true);
//do whatever you want with it
} | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 8,
"tags": "custom post types, custom field, query posts"
} |
wp_enqueue_script not loading my custom js file
I am using the following code below in my functions.php, However app.js is not found when I inspect it in the resources tab.
It is looking for it in <
when it should be looking in <
How do I modify this code so it looks in the correct directory, do I need to add get_template_directory_uri(); somewhere, I have tried but to no avail.
Thanks in Advance
p.s this is located in my functions.php file, since I read from here < that that is the proper way to approach including js files.
<?php
function load_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('my_javascript_file', '/javascripts/app.js', array('jquery'));
}
add_action('init', 'load_scripts');
?> | You need to reference your **WordPress template directory** when you register the script.
Change this:
wp_enqueue_script('my_javascript_file', '/javascripts/app.js', array('jquery'));
...to this:
wp_enqueue_script('my_javascript_file', get_template_directory_uri() . '/javascripts/app.js', array('jquery'));
Codex reference: `get_template_directory_uri()` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, wp enqueue script, directory, paths"
} |
wp_enqueue script my_javascript_file in the footer
I am trying to place `my_javascript_file` in the footer. According to the documentation `$in_footer` is the fifth value and it is a boolean so I have it set to `true`. Currently it doesn't show up anywhere, as far as I can tell from inspecting the code.
Got it to work, it was hidden in a div I forgot to close (oops)
UPDATE _added fourth parameter as empty string`' '`_
FUNCTIONS.PHP FILE
<?php
function load_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('my_javascript_file', get_template_directory_uri() . '/javascripts/app.js', array('jquery'),' ',true);
}
add_action('init', 'load_scripts');
/*add_action('wp_footer', 'load_scripts');/*DELETED THIS PART
?>
FOOTER.PHP added wp_footer
</div>
<!-- Main Row Ends -->
<?php wp_footer(); ?> /*added*/
</body>
</html> | You have `true` set in the 4th parameter (version), not the 5th.
wp_enqueue_script(
'my_javascript_file', //slug
get_template_directory_uri() . '/javascripts/app.js', //path
array('jquery'), //dependencies
false, //version
true //footer
);
Also, as someone else mentioned, drop jquery enqueue, you've got it as a dependency, you don't need to enqueue it as well.
One last thing, your function name has a good chance of breaking your site somewhere down the line. `load_scripts` has a pretty large chance of conflicting with something from the core or from the theme/plugin. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "wp enqueue script, footer"
} |
custom template rewrite
I have a page called `my-todo-list` and is using a custom page template.
The page is accessible via this type of URL : `
Now I need to paginate it, and I want to look like this: `
I've read a lot of questions here, but nothing clear.
Any Ideas to make it possible? my template needs something like`$page= $_GET['page']` ? | What you will want to use is `get_query_var( 'paged' )`. This will get the default pagination value, this should be set by default, so you should just be able to plug and play. Because there are no URL parameters due to rewriting, `$_GET[]` will be completely empty (at least on the example URLs). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "url rewriting, rewrite rules"
} |
Displaying Current Page Number Conditionally
I want to display the current page number in the site. I want it to be conditional though so that it doesn't show up on the home/front page. Using the code below, the page number is being displayed at all.
<?php
$pageNumber = (get_query_var('paged')) ? get_query_var('paged') : 1;
if(!is_front_page()) {
echo "<div class='page-count'><?php echo '– $pageNumber –'; ?></div>";
}
?> | You want to use `is_paged` which checks if the current page number is 2 or above (and returns true if it is). `is_front_page` checks 'if the main page is a posts or a Page'.
You've also used incorrect syntax (changed from a double quote to a single quote, and used `<?php` inside a string being echoed).
Untested, but the following should do what you want:
<?php
$pageNumber = (get_query_var('paged')) ? get_query_var('paged') : 1;
if(is_paged()) {
echo "<div class='page-count'> –".$pageNumber." –</div>";
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, navigation"
} |
How to have content scroll over background
I'm attempting to modify the latest version of the mystique theme, and would like to have it so when I select a background, the page will lock that background into page, but have the content scroll over top of it. Currently the content scrolls, but the background scrolls with it, leaving an awkward spot where the background no longer exists.
Would anyone know how this effect could be done? | I think you're looking for css's fixed background: W3 background definition
Here's an example from W3.
Something like this in CSS should work:
background: transparent url(images/bg.jpg) no-repeat fixed;
And if you want the background stretch/scale 100% width and height of user's screen, you should check some examples in here. See SolidSmile responde here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, customization, front end"
} |
filter custom post type by meta key in dashboard
I'm looking for a way to expand e customize more this topic
How to filter post listing (in WP dashboard posts listing) using a custom field (search functionality)?
I've a custom post type in the dashboard i've managed to have a small search box with a fixed search function to search a specific meta key. The things is that the search form appears on all the /edit.php pages while i need it only in the specific custom post type edit.php page.
I tried with
if (isset($_GET['post_type']) && $_GET['post_type'] == 'product')
but it doesn't seem to work. | I'm assuming you've used the method in the question linked to and are using the `restrict_manage_posts` filter.
add_action( 'restrict_manage_posts', 'my_search_box' );
function my_search_box() {
// only add search box on desired custom post_type listings
global $typenow;
if ($typenow == 'product') {
//On custom post type 'product' admin page.
//Add code for search box here
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, filters, search, dashboard, meta query"
} |
attach a PDF to an archives template?
I have a custom post type called "media" and I would like to be able to upload a single pdf called, "presskit" for the archive page that contains ALL of the media custom posts.
I only need to upload / associate a single PDF with the archive...it would be nice to make this is a submenu page, i.e. something like:
add_action('admin_menu', 'register_media_submenu_page');
function register_media_submenu_page() {
add_submenu_page( 'edit.php?post_type=media', 'Press Kit', 'Press Kit', 'manage_options', 'press_kit_file', press_kit );
}
function press_kit() {
echo '<div class="wrap">';
echo '<h2>Upload a press kit</h2>';
echo '</div>';
}
However, if this is too complicated I think the next best option is if the client could replace the pdf in the media library with a new pdf whenever they wanted to (keeping the same ID?) | I recommend this plugin all of the time even though I have no association whatsoever with the plugin or the author of it. It's free and allows you to add custom upload fields and all kinds of goodies to your edit screens without touching code. It's called Advanced Custom Fields. Some developers would frown upon suggesting a plugin instead of writing something yourself, but seriously why reinvent the wheel when there is a free solution already?
That plugin will do what you want and make it a hell of a lot easier for you and the client in the long run. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pdf, uploads"
} |
How to create a Wordpress plugin for another wordpress plugin?
I always do changes on the Wordpress plugins for clients. But these changes are always in danger to be lost if the plugin is updated.
Is there is a way to make a plugin for another plugin in Wordpress? Is there is a way to preserve the changes or re-apply it after each plugin update. | I think best way to do this is via actions and filters, like we extend WordPress core itself.
Other options is like @helgatheviking pointed, if plugin is class you can extend it.
Unfortunately not all plugin developers provide useful filters and actions with their code, most often plugin isn't written in OOP manner. Only way to save your modifications on plugin update, is to create copy of original plugin, change plugin name. I usually prefix original name e.g. `Mamaduka Twitter Connect`, but with this solution you'll need to manually update original plugin's code.
If you think that plugin needs more filters/action, you can contact the author and ask him to include those hooks into the core. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "plugins, plugin development, updates"
} |
wp_mail_from not changing from address
I wish to use the wp_mail_from hook to change the from email address submitted through a form which sends an invitation to a friend by email (I am writing my own plugin to do this).
I am using the following code to at present but I cannot see what I am doing wrong as the from email address is not set at all and goes to the default:
function() {
$this->from_email = $_POST['your_email'];
add_filter( 'wp_mail_from', array( $this, 'set_from_email' ) );
wp_mail( $to, $subject, $message);
}
function set_from_email() {
return $this->from_email;
}
As far as I can tell this should work flawlessly and out of the box but I have tried for hours at no avail hence, my question.
FYI I am using this function inside a class but I do not think that should change anything.
Many thanks, nav | After further investigation things seems to work with sendmail without the WP SMTP plugin. I have also been told by others that the WP SMTP plugin is needed to get email working on Windows hosts and is not needed if running your website on Linux. Hence, I think this was more to do with a specific plugin that to do with my code per se.
I think WP SMTP Mail gives the above behavior for security but I do not know enough about the SMTP protocol to comment further.
Thanks, nav | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugin development, filters, wp mail"
} |
How to load a post into an empty div tag anywhere across the pages?
Absolute beginner question: I need to load text into specific div tags across the page. On my html mockup its a lorem ispum text box waiting for wordpress to load the real content. So, how do i control the real content and its relation with the div box text on the page? Can it be a post, so i can manage it from the dashboard? Thanks in advance. | You can solve this in different ways.
One it's to use simple querys with WP_Query and using the **p** parameter to retrive a particular post like it's explained here. Something like this:
$the_query = new WP_Query( 'p=123' );
while ( $the_query->have_posts() ) : $the_query->the_post();
the_content();
endwhile;
Where 123 it's the post id from where you need the data (the_content).
Or you can query the content from a single post using get_post function. Like this:
$postid = 123;
$queryp = get_post($postid);
$content = $queryp->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
Where 123, again, it's the postid from where you need to extract the content.
And i think wp_get_single_post function should work too.
Then you can control your content everywhere just extracting the desired data from certains posts by postid | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, text"
} |
What is the advantage of using wp_mail?
What is the advantage of using `wp_mail()` over `mail()`. Codex says they're similar, but they seem to be _very_ similar. | `wp_mail()` is a pluggable function: It can be replaced by plugins. That’s useful in cases where the regular `mail()` doesn’t work (good enough), for example when you need extra authentication details. Example: WP Mail SMTP
`wp_mail()` uses PHPMailer by default, a sophisticated PHP class which offers a lot of useful preprocessing and workarounds for cases where `mail()` is too simple (UTF-8 encoded subject lines, attachments and so on). Just take a look at the bug tracker to get an idea about the complexity of these tasks.
`wp_mail` offers some hooks for other plugins to change different values:
* `'wp_mail'`
* `'wp_mail_from'`
* `'wp_mail_from_name'` use case
* `'wp_mail_content_type'`
* `'wp_mail_charset'`
* `'phpmailer_init'` _(an action)_
In short: **Use`wp_mail()` for interoperability.** | stackexchange-wordpress | {
"answer_score": 25,
"question_score": 24,
"tags": "plugin development, theme development, wp mail"
} |
when I create a page with a /blog permalink the css gets messed up
When I create a page with a default template and parent set to no parent, with the permalinks name being `sitename/blog` the css on that page gets messed up(including the admin bar is all messed up), if I change the permalinks structure to `sitename/blogs` it works perfectly fine. Also if I change the parent to another one of the pages with either permalinks name, the css works fine. Does /blog permalink register a weird parent or do something I am not aware other than the defaults. I have other pages with the same setup other than there permalinks name that work fine.
You can view the broken site here password: springy88 **click the blog link**
Thanks in advance! . | On your wordpress menu use another class instead of "blog" for the blog item, cause your theme has a function that add a similar class to the body so it's creating a conflict in there, try erasing your blog class for you to notice.
Also the app.css if for ur custom css :), no need to use both. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, css, blog, parent theme"
} |
What is the difference between the "wp_footer" and "get_footer" actions?
I am working on developing a plugin, and I am trying to add a line of text to the bottom of the page, I see there are two actions that seems reasonable, `wp_footer()` and `get_footer()`. wp_footer sounds like it may more suited towards code that needs to go at the very end of the page (like JavaScript files), but get_footer didn't have any documentation on its wordpress codex page. Which should I use for something like this? | These two functions accomplish two different things. `wp_footer()` is a hook used in your footer.php template file to ensure that the right code is inserted (from the core/plugins/etc) into the right place. `get_footer()` is used in your other template files to call for the code in your footer.php template file.
So in simpler words `wp_footer()` gets other code that you most likely don't produce (but need), so it's a little more abstract. `get_footer()` grabs the exact code that you wrote into your footer.php file so it is the WordPress version of PHP's `include()` function.
Hope this helps :) | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 9,
"tags": "plugin development"
} |
Image Manager Plugin
I'm looking for a simple plugin that allows me to manage groups of images. Wordpress does this, but you would need to link the gallery to a page or post. Since i'm looking to create a site banner with dynamic images, i don't want to link a gallery to an specific page.
Is there a good image manager plugin for this simple task or do you know a way to do it natively in wordpress? | You could try the Media Library Categories plugin to add categories. It does a wonderful job of adding category functionality, but the code could be improved upon and custom implementation requires some knowledge of PHP, as it only provides you with a shortcode and no documentation.
This Question, maybe be able to help you if you choose this solution. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, images, gallery"
} |
anchor tag in header not working on other pages except the home page
I have a anchor tag that wraps around my logo image that takes you back to the home page using the following
`<a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/logo.png" alt="Good Morning Moon"/></a>`
It is inside my header.php file. On my home page which is a staid page set to custom template with the following code it works
<?php
/*
Template Name:Home Page
*/
?>
<?php get_header(); ?>
<?php get_footer(); ?>
However on any of my other pages which are using the default template which I assume is the index.php file I have setup based on looking at the < the anchor tag does not show up, my index.php file looks like so
<?php get_header(); ?>
<?php get_footer(); ?>
What could be causing this? | The code you're posting _should_ work, as far as I can tell; however, you're using some outdated template tags.
Try replacing `bloginfo( 'url' )` with `echo home_url()`, and `bloginfo( 'template_directory' )` with `echo get_template_directory_uri()`, like so:
<a href="<?php echo home_url(); ?>">
<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="Good Morning Moon"/>
</a>
For more specific instruction, it would be very helpful to see the _full_ code of the _actual_ template/template-part files in question. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, links, template hierarchy"
} |
Permalink Structure not updating .htaccess
I am trying to update the permalink structure using the back-end and Settings -> Permalinks. The `.htaccess` file is not updating.
I have given `.htaccess` full access with `chmod -R 777 .htaccess` and still, Wordpress says that the permalinks are updating, yet they aren't coming through. When I click, I'm still getting 404s from `apache2`. | If you have given the correct access and the problem still isn't resolved, but WordPress says that it is indeed modifying the file I think you should double check and make sure the rewrite_module is on. If you're site is live and you're having this problem you need to call your hosting service and they'll be able to help you. However, if you're local, I think I can help you :)
I once had this problem after I started trying out WAMP and I tried everything you stated above. Here's what I did: left click on the tray menu icon, go to Apache > Apache modules, then scroll down and make sure rewrite_module is checked. If it is not, check it. WAMP should then restart and (in theory) your problems should go away!
Good luck! Write back and let us know if it worked! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks"
} |
wp_list_categories with show_count, except for specific categories
I want to show post count for all child categories shown, but not for their parent categories. Or, since there are only 3 parent categories, this exclusion could be per category id.
Is there a way to do that?
Also, unfortunately, the number doesn't come wrapped in any element, so I can't think of any way of hiding it CSS wise. | Check out this post. It shows you how you can wrap the count with any element you'd like so that you can manipulate it as you see fit. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
Should Plugin Folders Include a Blank index.php File?
WordPress itself, in the `wp-content` folder, includes an empty PHP file which looks like this.
<?php
// Silence is golden.
?>
Should plugins include an empty file like this as well to stop folks view viewing the contents of a directory? What about additional folders in themes -- like an `includes` directory? | No, they should not. If a plugin has vulnerabilities just because someone might see its directory structure it is broken. _These_ bugs should be fixed.
Security through obscurity is a bug for itself.
It’s up to the site owner to allow or forbid directory browsing.
A second issue is performance: WordPress **scans all PHP files in a plugin’s root directory** to find plugin headers. This allows you to have multiple plugins under the same directory, eg `/wp-content/plugins/wpse-examples/`.
It also means that unused PHP files in that directory are wasting time and memory when WordPress is searching for plugins. One file will not do much harm, but imagine this is getting a common practice. You are creating a real problem in an attempt to fix a fictional. | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 17,
"tags": "plugin development, theme development"
} |
how can I add a "read more" tag directly in the template?
how can I add a <\--more--> tag directly in the template? I mean, the exact php code to use in a template for that shortcode. I need it for a script that makes use of that shortcode to hide content and having to add the "more" shortcode by hand through all the posts would be such a task
any help appreciated! | The code would probably be something like this:
echo '<a href="' . get_permalink() . "#more-{$post->ID}\" class=\"more-link\">".__( 'Read more >', 'your-theme' ). '</a>';
Check out the source on how WordPress does it: <
This has to be inside the loop to work and the `$post` global has to be visible in the current scope. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates, shortcode, read more"
} |
Multiple post back-to-back display only one gallery
I have 3 post, post1=text, post2=text and gallery1, post3, text and galery2
I like to list ALL the post from one category, and the result is all the data get out, but the gallery associated with the post is ALL THE SAME. yep the second post and post#3 have the same picture...
the problem, the shortcode of gallery is associated with post, but with all the post display in a single page, the gallery are not specific
what i have done wrong ?
some code :
//Add a ShorCode to get a page/post content
add_shortcode ('page','get_page_content');
function get_page_content ($att) {
if (is_array($att)) { $req_id = $att['id']; }
else { $req_id = $att; }
$post = get_page($req_id);
$content = apply_filters('the_content', $post->post_content);
return $content;
} | Hourray : find it : do_shortcode do the trick !
here is the final code :
// --------------------------------------------------------------------------------------------------------------------
//Add a ShorCode to get a page/post content
add_shortcode ('post_cat3','get_post_cat3');
function get_post_cat3 ($att) {
$query = new WP_Query( 'cat=36' );
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
$aaa .= '<p>------------</p>'.do_shortcode(get_the_content());
endwhile;
endif;
return do_shortcode($aaa);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, gallery"
} |
The result of a shortcode appear BEFORE page content
I have a page, with a shortcode that get all the post from a categorie and put after the content of the page. For no apparent reason, the result of a WP_Query() in the shortcode APPEAR ALWAYS at the top of the page. If i put the shortcode a the top OR at the bottom, the post (3 of them) appear before the content of the page...
on that one, i have NO IDEA why... shortcode is at the en of the page
* * *
after the comment i post the code the ECHO... this is the problem ?.. i to solve it ?
//Add a ShorCode to get a page/post content
add_shortcode ('post_cat2','get_post_cat2');
function get_post_cat2 ($att) {
$mypost = array();
$args = array( 'category' => 36 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
$mypost .= the_title();
endforeach;
return $mypost;
} | codex the_title()
replace this
$mypost .= the_title();
with
$mypost .= the_title('','',false); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode"
} |
How to check if user is in back end?
In my application, i have one form. Now if user is in front end i want to display the title but if he is in back end i do not want to display it.
I do not want to check it based on user role. | Use `is_admin()`. It checks if you're viewing an Admin page, means the backend. | stackexchange-wordpress | {
"answer_score": 33,
"question_score": 20,
"tags": "plugins, admin, user access"
} |
Couldn't find a documentation for a filter API in plugin development
I'm new to wordpress plugin development, I read the whole documentation this afternoon < I tried to write some code, like this in plugin file:
add_filter('the_title', 'my_own_function', 10, 2);
**Function is:**
function my_own_function($title, $post_id){
return $title. $post_id;
}
This plugin really worked, but the documentation doesn't tell the filter API `the_title` has two arguments, and what those arguments are. That's the problem! If it doesn't tell, how would I know?
**Here I just quote the official documentation relevant excerpt:**
the_title
applied to the post title retrieved from the database, prior to printing on the screen (also used in some other operations, such as trackbacks).
So, my **question is:** How can I find a full explanation of filter API such as `the_title`? Please help. | There's only one answer: **You always go and read the source code**.
There are some online tools that help you with this, specifically Adam Brown's Hooks List, which contains links to the source code where you can read what arguments filters and actions take.
Be aware that a single filter can have variable amounts of arguments depending on where it is being used. For example, in class-wp-posts-list-table.php `the_title` filter sends out one argument only, instead of two like in post-template.php
So, again, always read the source specifically on where the filter is being applied. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Close modal window after form submit
I have this in a php file from Contact Form 7, which **I load into a modal window** (FancyBox) and **I would like to close it after the user will press the Submit button**.
I was thinking of adding onSubmit="action" to the form but I don't know how or which one is the function I am supposed to use to close the modal window?
$form .= '<form action="' . esc_url_raw( $url ) . '" method="post"' . ' class="' . esc_attr( $class ) . '"' . $enctype . '>' . "\n";
Is this the right approach?
Also, if I can make it to click on a PayPal button right after that, it will be brilliant. | Contact form 7 Lets you call a JavaScript function after the form has been submitted You will find the Additional Settings field at the bottom of the contact form management page and you need to use the hook named `on_sent_ok` something like this:
on_sent_ok: "$.fancybox.close();" | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, forms, plugin contact form 7"
} |
How Do I Use A Custom Mobile Theme?
I have a self hosted blog and I want it to be mobile compliant. I know there is a free plugin the serves this purpose. However, I want to use a simple mobile theme I like (say from Theme Forest). How do i go about it? Is it as straight forward as uploading a normal theme? | This depends on the theme in question,
* Some themes have a desktop and mobile versions built in.
* Some themes are made to fit the screen size (responsive).
* Some themes (for mobile) come as a plugin which activates it self when the user access the site from a mobile device.
So In the either way its a matter of activating and configuring the theme or plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, theme options, mobile"
} |
Using Orderby and meta_value_num to order numbers first then strings
I have a list of products, each with a price in a custom field stored as text such as "2.50" or "5.00" and I am displaying them on the page with a custom query that sorts by the price:
if(!$wp_query) {
global $wp_query;
}
$args = array(
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
query_posts( array_merge( $args , $wp_query->query ) );
This works fine for the prices, but some prices are "POA" and I would like to show them last, however the above orders in such a way that "POA" is shown first.
Is there any way to alter this, or a quick hack I could use to sort the array afterwards and put any "POA" prices last? | The `OrderBy` argument can take more then one parameter so the solution was to change :
'orderby' => 'meta_value_num',
to:
'orderby' => 'meta_value meta_value_num', | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 17,
"tags": "order"
} |
Restrict access to non-wordpress section of site with user roles?
Is it possible to limit access to a page using wordpress user roles that isn't included in the wordpress install.
For example I have a CS Cart install with only a couple of products but I need to limit access to these pages to certain users.
Can I add something in to my CS Cart install to call on Wordpress to be able to limit access if the user is just a subscriber? | if you can include the `wp-load.php` from WP install; after this you can use all WP Core functions and can also check the user and his rights with core function - `current_user_can()`.
But maybe it's easier to create an bridge from CS Cart to WP, if CS Cart has an own user table; i dont know. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, user roles, customization"
} |
Attaching a metabox to a single post
I've been using metaboxes for a while now, and enjoyed their flexibility. However, I am now in a situation where I need the metabox to appear only for **a specific single post or page** , and **not** for the whole (custom)-post-type. Is it possible to do so?
Your kind assistance would be most welcomed.
TIA Matanya | Since you are familiar with the how to create metabox using `add_meta_box` already, I'll skip to the relevant bits.
You can either conditionally `add_meta_box` depending on the current post title, or ID, (this is the preferred method) or, you can conditionally `remove_meta_box` depending on the the post displayed.
To detect the current post ID you would `get_query_var( 'post' )` and move on from there, using `get_post(get_query_var('post'))` if further post data is required to filter out the metabox. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "metabox"
} |
Categorize posts on a page o the basis of category of other post on the same page
I will explain the problem more clearly. I want to create a page which will show three blocks.
At the top: It will show one post . ( An issue of a Magazine. PDF in a post)
At the center: It will show all the articles from the magazine. ( Posts from the issue of magazine)
At the bottom: It will show other issues of magazines.
How to solve this problem? I thought of having one category for each issue of a magazine and the articles belonging to that magazine. Is it feasible? | I'd say you'd be looking at custom post types. Google custom post types and taxonomies and do a bit of study on that front and then you should know more about what you want to actually display. I could be misunderstanding you but doubt if categories in the blog is where to go with this, CPT's do something similar but are much more flexible. If you work out a structure that suits you in terms of CPT's then getting it to display how you want on whatever template pages you want is not going to be incredibly difficult, but you need to work out the structure that you use to store them in WordPress first. I would advise the **Custom Post Types UI** plugin as a way to play around. Then you may want to keep that or else it can give you custom code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters"
} |
Custom Page Templates
I am trying to find the feature to add a page template. I am adding an archive but when I go into pages->Add New-> I get no option in the sidebar to use the existing archives.php file I want to use. Can anyone help me out? | `archives.php` is a template file that WordPress will use by default (if it exists). If you want to create a custom page template you need to create a new template file in your theme. You can read all about it in the Codex, but I'll provide an example below. Put this at the top of your new file:
<?php
/*
Template Name: Your page template name goes here.
*/
?>
Then follow it with the custom code you need to display your data.
Then, when creating a new page that you would like to use the above template, you will see a drop-down list on the right that lists all the names of page templates you have in your theme. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "page template"
} |
Making that Admin Bar transparent or a blue color
The question title is pretty self-explanatory - I don't really like the new Admin's bar's colour but I find it useful and want to keep it so I would like to change the colour of it. However, I'm not the best at web scripting, let alone CSS so I wondered if anybody here would help me to make the Admin Bar the following sort of HEX color: #62BACE.
If that color isn't really possible, or it is easier - I wouldn't mind having a transparent admin bar!
Any assistance would be very kind and grately appreciated!
Thanks in advance
PS If there's a plugin that does this for me I wouldn't mind using it - I just don't know of any and can't code in CSS... | There's a good plugin to make the admin bar blue in both the admin and front-end: <
If those colors don't suit, play around with the plugin to figure out how to do your own. The key thing to notice about the plugin version is that by using a hook to enqueue the stylesheets, it's possible to get the dashboard version as well -- adding to your theme's css will only affect the front end. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, themes, css, admin bar"
} |
Page template not registering on theme
I have the following code for a page. When I select the template Home Page from the drop down menu in the page edit, it doesn't work on my web host, but locally it works fine, so I don't think it is my code. I don't know why its not working though.
<?php
/*
Template Name:Home Page
*/
?>
<?php get_header(); ?>
test
<div class="row">
<div id="welcome" class="seven columns centered">
<?php
$page_id = 2;
$page_data = get_page( $page_id );
$content = apply_filters('the_content', $page_data->post_content);
echo $content;
?>
</div>
</div>
<?php get_footer(); ?> | Might be a difference in query methods. This is a simpler way to query a page's content and can be used multiple times in a template without each query conflicting with each other.
<?php $my_query = new WP_Query('page_id=2'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "templates, user registration"
} |
What would cause edit buttons for plugins to disappear?
in the plugins page, under each plugins' name usually there are buttons/links like "Deactivate | Edit | Settings". Recently on one of my sites the "Edit" (and "Settings") button has disappeared. I have just "Deactivate" or "Activate | Delete".
My question is - what could cause this?
I am logged in as an administrator, so I should see the buttons. I suspect that something might have vent wrong with the installation of the last plugin but I am not sure.
Is there some scenario when these buttons get disabled (hidden) or do I have a bug / error? | Edit buttons display only when the necessary file permissions are acquired by PHP.
<
`is_writable(WP_PLUGIN_DIR . '/' . $plugin_file)`
`current_user_can('edit_plugins')` will always return false if the `DISALLOW_FILE_EDIT` flag is set to true (recommended) in the configuration, no matter if you're the administrator or not.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, admin"
} |
Removing fields from the Media Uploader/Gallery
I've been searching high and low for an answer.
I simply want to remove the Alternate Text, Caption, Description and Link URL-fields from the uploader and gallery view.
I seem that every thing else than this Media-thingy can be removed.
Thanx for helping out:) | You can do this via a filter. Add the following to functions.php. You can also add your own fields this way...
// edit fields in media upload area
add_filter('attachment_fields_to_edit', 'remove_media_upload_fields', 10000, 2);
function remove_media_upload_fields( $form_fields, $post ) {
// remove unnecessary fields
unset( $form_fields['image-size'] );
unset( $form_fields['post_excerpt'] );
unset( $form_fields['post_content'] );
unset( $form_fields['url'] );
unset( $form_fields['image_url'] );
unset( $form_fields['align'] );
return $form_fields;
}
The example above strips out more than you need to but if you do a `print_r()` on the `$form_fields` variable you'll see what's available to add/remove. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "customization, wp admin"
} |
wordpress alchemy put custom metabox on certain page only
I want to put the custom metabox I have only on the home page but I am not sure how to go about doing this. I am using the following to add the custom meta box to all the pages. How would I select just the home page, or home.php template or that ID. I am really just not sure of the syntax.
<?php
$custom_mb = new WPAlchemy_MetaBox(array
(
'id' => '_custom_meta',
'title' => 'Add images to home page slider',
'template' => get_stylesheet_directory() . '/metaboxes/custom-meta.php',
'types' => array('page'),
));
?> | new WPAlchemy_MetaBox(array
(
'id' => '_custom_meta',
'title' => 'My Custom Meta',
'template' => STYLESHEETPATH . '/custom/meta.php',
'exclude_template' => 'product.php'
));
the 'exclude_template' would work for excluding the one's you didn't want.
new WPAlchemy_MetaBox(array
(
'id' => '_custom_meta',
'title' => 'My Custom Meta',
'template' => STYLESHEETPATH . '/custom/meta.php',
'include_template' => array('product.php','press.php') // use an array for multiple items
// 'include_template' => 'product.php,press.php' // comma separated lists work too
));
including works the same.
Here's how you'd include only by post ID (Which if you're designing this for a client I wouldn't do they tend to break the Post ID's by midweek).
'include_post_id' => 97
Here's a link: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "metabox, pages, homepage"
} |
remove menus for a specific role?
I saw this snippet to remove menus:
function remove_menus () {
global $menu;
$restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
end ($menu);
while (prev($menu)){
$value = explode(' ',$menu[key($menu)][0]);
if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
}
}
add_action('admin_menu', 'remove_menus');
Is there a way to restrict specific menus, but just for the "editor role"?
I tried something like:
$_the_roles = new WP_Roles();
$_the_roles->remove_cap('editor','moderate_comments');
But I still see the comments menu... | Here is your answer:
function remove_menus () {
global $menu;
if( (current_user_can('install_themes')) ) {
$restricted = array(); } // check if admin and hide nothing
else { // for all other users
if ($current_user->user_level < 10)
$restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins')); // this removes a lot! Just delete the ones you want to keep showing
end ($menu);
while (prev($menu)){
$value = explode(' ',$menu[key($menu)][0]);
if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
}
}
}
add_action('admin_menu', 'remove_menus');
You can tailor this to suit whatever role the user has by adjusting the if( (current_user_can('install_themes') argument
See here for more < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, user roles, permissions"
} |
How to Automatically import external images to Upload
Hi to all I would like to have a simple plugin, hook, anything that Automatically caches external images. Simple explanation: Actually I'm using this plugin: < But with this I have to click on scan, then choose which images I would like to save then wait and so on... I'm in need of something more automatic. Is there anyone who can teach/tell me how to do it? Thank you! | If you look at the Cache Images plugin's thumbnails page on the WordPress plugin directory it looks like this feature already exists within the plugin. In the admin section of your site go to Settings->Media there should be an option to cache images when posts are saved.
! Cache Images settings for automatic caching | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, cache, cron, remote, autosave"
} |
How to split up the_title and insert a span tag
My titles, site wide, will follow this theme all within a h1 tag:
Main title heading / Sub-title text
I'm trying to wrap a span tag around all text after and including the '/' so my markup will look like this:
<h1>Main title heading <span>/ Sub-title text</span></h1>
How do I accomplish this? I'm not great with PHP but I've tried playing with explode but can't get the end result all I end up doing is hiding everything after the '/'
**EDIT:** Code removed & Pastebin created, this is my whole page for index.php: < | its best if you just use **custom field** type to create a sub title...
That way you leave the title un-touched and just add a field where you can insert a value like so (calling field sub title):
!enter image description here
* * *
Then you can fetch your subtitle easily:
<?php
$sub_title=get_post_meta($post->ID,'subtitle',true);
if($sub_title != '') {
echo '<h1>'. the_title() .'<span>'. $sub_title .'</span></h1>';
} else {
echo '<h1>'. the_title() .'</h1>';
}
?>
.
i hope this a suitable solution for you... i use it on occasions
Cheers, Sagive
* * *
**HOW TO:**
Replace (i hope it looks the same in your theme) with the code above..:
<h1><?php the_title(); ?></h1> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "get the title"
} |
which theme is this?
Could anyone help me finding which WP theme has been used in this site?
<
I only have found concerning a DM theme but I really haven't been able to find it anywhere
thank you Mari0 | It appears to be a modified version of DM's CircloSquero theme. DM doesn't seem to have it available anymore, but Theme Forest has it for download here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "themes"
} |
A good Wordpress theme development book recommendation
I am looking for a good recommendation for a wordpress theme development book. i have some experience building themes, but I want to learn more, and have trouble reading or understanding the codex sometimes. I don't know that much php, so a php recommendation would also be nice. Thanks in advance. | I can recommend Digging into WordPress (it covers the whole WP dev) and Rockstar WordPress Designer (part 1 and 2), both are available in e-book/pdf format. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "books"
} |
Permalink doesn't get displayed in Twitter button (Local WordPress problem?)
I'm trying to add a custom "Tweet this" button to my WordPress posts. I'm sticking to the official Twitter guidelines.
Here is what I'm actually trying to pull of; I don't want the button, I want a custom look - for me it's _only text_. This is the code I use:
<a href=" echo urlencode(get_permalink($post->ID)); ?> &text=<?php the_title(); ?> &via=username&count=horizontal" class="custom-tweet-button">Tweet</a>
**Output:**
> This is the post title via @username
So the problem is that the permalink (`<?php the_permalink(); ?>`)doesn't get displayed.
I tried:
* ` echo urlencode(get_permalink($post->ID)); ?>`
* ` the_permalink(); ?>`
PS: I also tried the standard twitter button, not the custom one, but the permalink doesn't get displayed either.
Does anyone one if something is wrong with my code or if this is a problem since I'm using a **local WordPress** for development? | After sleeping over the problem I decided to the code and tried this:
<a href=" the_title(); ?>: <?php echo urlencode(get_permalink($post->ID)); ?> &via=username&count=horizontal" class="custom-tweet-button">Tweet</a>
All I can say is: it works as it should be. Next thing on my agenda is to incorporate a custom url shortener.
PS: It's worth a mention that if you use certain themes, they might use a special %permalink% and %post-title% structure. Be sure to replace the default `<?php the_title(); ?>` and `<?php the_permalink(); ?>` with it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, permalinks, urls, twitter, buttons"
} |
How to translate multi-line strings?
If there is a long string in PHP like this:
<?php
$text = "Some ... very
very...
long string";
Can it be localized by GetText wrapping it in `__()`, e.g.
<?php
$text = __("Some ... very
very...
long string", "domain");
? I've heard that GetText doesn't support multi-line strings and indeed, when I try to scan such file in poEdit, it doesn't find it.
How do you deal with that? WordPress source files seem to use very long lines so is that the way to go? (Obviously apart splitting the strings into multiple smaller strings which I'd rather avoid.)
**Edit** : the problem was that I had a variable reference in my string, e.g. `__("string $someVar")` which can't be supported by GetText. My fault. | `__()` and the other l18n functions will handle any string you give them, including line breaks. In my experience, poEdit recognizes them just fine, but if you're having issues, you may consider using UNIX line break escapes `\n` instead of actual line breaks inside the strings; in this case, be sure to use double quotes, so that they're not rendered literally. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "localization"
} |
Auto 301 to full post permalink? (using /posts/%post_id%/%postname%)
I update my permalink structure to /post/%post_id%/%postname%, but if someone uses a URL like /post/1234 instead of the full URL of /post/1234/bingo-rulz, WordPress shows the post without giving a 301 to the full URL. Isn't this poor SEO? Sites like tumblr and stackexchange auto 301 to the full URL. Any hacks/code/plugins/settings/etc to fix this? thanks
p.s. /post/1234/blah does get a 301 to /post/1234/bingo-rulz but /post/1234 does not and ends up in two separate URLs to the same content. | Think I found a solution... Since anything after the %post_id%/ ___ _ will redirect to the full slug, a simple RewriteRule in the .htaccess file appears to do the trick. I had to place it above other RewriteRules and this is working for me.
RewriteRule ^post/(\d*)/?\z$ < [R=301,L] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, url rewriting, htaccess, redirect"
} |
is there a plugin that allow editing pages from within pages without entering admin panel?
Is there a plugin that allows editing pages/posts without going to admin panel?
I've a specific need to disallow access for users to admin panel of wordpress/multisite users. But I want them to be able to change contents of pre-structured pages.
is this possible? anyone already thought of this before me?? | Have you tried the Front End Editor plugin to allow users to edit the pages on the site?
> Front-end Editor is a plugin that lets you make changes to your content directly from your site. No need to load the admin backend just to correct a typo. You can edit posts, pages, custom post types, comments, widgets and many more elements. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Any Wysiwyg tool to edit wordpress site based on given theme?
I dream of a wordpress dashboard that would be mostly Wysiwyg and let the user edit a site based on a given theme.
In fact this is something I know is technically possible as I have seen it in this tool: < (see the video; it is not a wordpress tool, but it shows how one can edit a webpage underlying code with a Wysiwyg interface).
For example if I am using WooThemes Optimize, the dashboard would show me the homepage and let me edit the titles, the text in the button, the featured image, etc.
Does anyone know a tool that can do that? or any hint how I can get there? | Just found this: <
apparently they call this a "WYSIWYG theme platform".
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wysiwyg"
} |
Adjust query on single
I am building an event manager. One of the template files I have is events-single.php which displays single events. At the bottom of this I have next and previous events using `next_post_link` and `previous_post_link`. The problem is that those functions proceed through the events in order of **published date** rather than **event date**. (I have a meta key `_fulldate` setup on the CPT for this). When I was building events-archive.php file I overcame a similar problem by doing something like this
$query = new WP_Query( array (
'post_type' => 'events',
'orderby' => 'meta_value',
'meta_key' => '_fulldate',
'order' => 'ASC')
);
However when I try that on events-single.php it makes all the events display on the page.
Ultimatly I want events-single.php to behave like a single page but then allow me control over the query as above. Is this possible or will I have to do a second loop for the Previous and Next links | Take a look here: specify meta_key / meta_value condition for prev_post_link and next_post_link
Which ultimately leads to this plugin, which accesses the get_adjacent_post function mentioned above: Ambrosite Next/Previous Post Link Plus
And looks like it would fit your needs by allowing you to specificy a meta_value for the next/prev post hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, theme development, wp query, metabox, post meta"
} |
What hooks, actions or filters i can use to customize wordpress registration page and form?
i would like to customize the design of the registration page of wordpress and also the registration form. Can i create a registration page template? or maybe tell wordpress to use a custom registration page i create. | WordPress handles registration with wp-signup.php (in the root of the installation). There are some hooks in place to allow for additional content (such as a signup header, or additional signup fields), but it doesn't support theming in the same way that other WP pages do.
BuddyPress is a pretty heavy-duty solution if all you want is a custom registration page (so I won't suggest that you install it on your site), but you might want to check out how it handles registration. Essentially, it provides its own template for registration (which you could do with a Page Template in WP), and then has some functions for handling some of the things that wp-signup.php does inline. See especially buddypress/bp-members/bp-members-signup.php. Using a totally custom registration process like this means that you can do pretty much whatever you want. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user registration, templates, template redirect"
} |
How to check if a shortcode exists?
I'm using `do_shortcode` function to add shortcode in my template. But i would like to check if that shortcode exists before display them.
I mean like this
If (shortcode_gallery_exists) {
echo do_shortcode('[gallery]');
}
Can anyone help me? Thanks | #23572 introduced shortcode_exists() into 3.6. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 6,
"tags": "templates, shortcode"
} |
Best Plugin to Reorder Post Types
I'm looking for a plugin that enables me to reorder pages, posts and custom post types from the normal listing in the WordPress dashboard.
The closest plugin I've found is Simple Page Ordering < however this plugin does not allow post ordering, and also does not easily allow building hierarchies.
So I'm looking for a plugin that does the above but adds support to posts and also enables hierarchies. I like the way the WordPress menu builder lets you add hierarchies by moving a sub page to the right until it attaches itself as a sub-menu.
Another plugin, CMS Tree Page View, does this very well but has its own interface, while I'd prefer using the native interface of WordPress.
Any suggestions? | I've used the below plugin and it has worked really well for me:
Post Types Order
It just adds a "Reorder" option in the sub-menu for posts and custom post types and has drag/drop functionality. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "order"
} |
Admin Panel pagination link styles
Whenever I write plugins that use Admin Panels, I include some form of pagination using the `paginate_links` method and I have always been able to style them in a nice way using the suggestions on this blog post. Recently, however, I have been unable to find the secret sauce to make this work. I'm guessing it's the way the divs on my pages are set.
Does anyone have the proper style declarations for using real WordPress pagination links? (Look at that site for what I'm looking for) | Fantastic, once again researching my question has provided an answer. For those interested, surround your pagination links in `<div class="tablenav"><div class="tablenav-pages">LINKS</div></div>` to get better looking number links.
(moved to answers as suggested by SickHippie) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, admin, pagination, css"
} |
Upload multiple images in a custom metabox
I am new to theme development. I am trying to create a custom metabox that has the ability to upload a image. I am doing this on a page not a post. I want to output the images (multiple) onto the page in a unordered list. I have attempted to use WP alchemy, and I can only get as far as getting the metabox to show up but I have no idea on how to output the imgurl to the page. Is there a better way to upload multiple images to a page which is easy for a client and doesn't add images to the content editor (I just think it isn't user friendly) and then output them to a page in a unordered list. Some advice please. | That's pretty advanced and it doesn't sound like you are all that comfortable with WP yet, no offense. You can definitely do this with WP Alchemy (I have and do), but you really have to get down and dirty with some Javascript to 1. launch the media uploader and 2. to hijack the send to editor function.
some good reads:
<
<
As far as alternatives: you might want to try the the Metabox class by Rilwis.
<
or Advanced Custom Fields <
Both are much less DIY than Alchemy. I'm pretty sure the one by Rilwis even has the plupload drag and drop uploading and a simple way to turn on repeating fields. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "images, metabox, pages, uploads"
} |
Is it possible to add an item the Post Publish panel?
In the Admin area when you edit a post, I'd like to add a custom item to the Publish panel in the top right corner.
Is it possible to access this through the Wordpress API? If so, what functions do I need to look at? Any examples would be much appreciated. | You can hook into `'post_submitbox_misc_actions'` or `'post_submitbox_start'`:
add_action( 'post_submitbox_misc_actions', 'wpse_45720_submitdiv_extra' );
add_action( 'post_submitbox_start', 'wpse_45720_submitdiv_extra' );
function wpse_45720_submitdiv_extra()
{
print '<pre>' . current_filter() . '</pre>';
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "wp admin"
} |
add_theme_support( 'admin-bar' ) causes fatal error
I am trying to learn more on Theme Development so I've created my own and everything worked fine except when I added `functions.php` and tried to update it with something simple as:
<?php
add_theme_support('admin-bar', array('menus'));
?>
I get `Server 500 ERROR` and I cannot access any part of Wordpress, not even Dashboard. But then as soon as I delete `functions.php` and refresh page my Wordpress is back again and working smooth.
What is so mysterious about `functions.php`????
Thank you so much. | Error 500 is very generic and can be caused by numerous underlying issues. Your first step should be locating error log for your hosting account or asking support to help with that.
My weak guess would be that your file gets created with file permissions that are not secure enough to hosting configuration. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, internal server error, add theme support"
} |
When to use custom DB tables or add_option?
I've got a pretty straight forward question. When does it become too much data to use `add_option`, `update_option`, etc, and instead use a custom DB table?
For example, if a plugin stores thousands and thousands of characters of data using `add_option`, etc, is there a maximum it can handle before it starts to create problems?
A plugin of mine used to create its own DB table, but it created a lot of issues in which some users setups wouldn't work (especially on Microsoft based hosting servers), and many more users felt the need to contact me and advise me on using `add_option` instead. I followed their advise, and now the plugin uses these functions.
However, I've come a long way in my coding abilities since then and in-turn have started redesigning the plugin. It now has much, much more data to be stored using `add_option`. Even up to over 10000+ characters worth, and I'm beginning to wonder if it will cause any problems. | For the record, I will **_never_** encourage developers to use custom database tables. Yes, they're easy to use, but you lose 100% of the data abstraction provided by WordPress.
`add_option()`/`update_option()`/`get_option()` are basic key-value functions. They store data in a MySQL LONGTEXT field. LONGTEXT can store over 4 million characters ... so a 10000+ character option is definitely possible. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, options"
} |
Creating my own portfolio custom-type
I'm using WordPress to build my photography portfolio. So far I've created a _Custom Post Type_ called `session` for each photo session, and I've managed to list all the sessions with each thumbnail in the home page.
Now, however, I have to create the content of each `session`. I'd like to keep it simple:
* The title
* A small description (if any).
* A set of pictures, that should appear straightaway in the post.
The problem is that I don't know how to face the inclusion of the images. Looks like using a _gallery_ is not what I'm looking for, because it generates a set of thumbnails, and I just want the images in full size in the post.
What's the best way of doing this? The ideal case would be to have something like `the_images_of_this_post()` so I could place them at will from the template file.
Thanks! | Attachments are post objects, with `post_parent` set to the ID of the post they belong to (ie your 'session'). The WP Codex page on `wp_get_attachment_image()` has an example almost exactly like what you're trying to do: < Make sure that you replace the `post_parent` parameter in that example with the ID of the current session (which will probably be `get_the_ID()`, though it depends on how your loop works). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, gallery"
} |
how to programmatically change post tags
Is there a php function which can add/remove tags of posts? If not how would I do this?
I am looking for something like this:
add_tag($post_id, 'tag-name');
remove_tag($post_id, 'tag-name'); | The key function you're looking for here is `wp_set_post_tags()`.
To add the tag 'awesome' to post 98,
wp_set_post_tags( 98, array( 'awesome' ), true );
Note that the `true` parameter means that this tag will be added to the existing post tags. If you omit this value, it defaults to `false`, and the existing post tags will be overwritten with the new ones being passed.
To delete a tag, first pull up a list of the existing post tags using <
$tags = wp_get_post_tags( 98 );
Then assemble a list of the tags you want to keep (which will exclude the one you're "deleting"), and replace the existing post tags with the new list:
$tags_to_delete = array( 'radical', 'bodacious' );
$tags_to_keep = array();
foreach ( $tags as $t ) {
if ( !in_array( $t->name, $tags_to_delete ) ) {
$tags_to_keep[] = $t->name;
}
}
wp_set_post_tags( 98, $tags_to_keep, false ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "posts, tags"
} |
get_the_post_thumbnail('thumbnail-name') always returns empty string
I need to duplicate a list of thumbnails elsewhere on a page and have set up a few different custom thumbnail sizes in my functions.php file.
If I use:
the_post_thumbnail('photo-small');
Then the thumbnail gets displayed correctly, if I use:
echo get_post_thumbnail('photo-small');
Nothing gets echoed - it's an empty string.
What I am trying to do is add the generated img tags to an array so that I can loop through it outside of the loop but for some reason it's always blank. | You're using `get_the_post_thumbnail()` and not the nonexistent `get_post_thumbnail()` function, right?
As JohnG said, you _have_ to pass the ID of the current post to `get_the_post_thumbnail()` (the `the_post_thumbnail()` function already handles that for you). The Function Reference in the WordPress Codex has many usage examples:
get_the_post_thumbnail($id); // without parameter -> Thumbnail
get_the_post_thumbnail($id, 'thumbnail'); // Thumbnail
get_the_post_thumbnail($id, 'medium'); // Medium resolution
get_the_post_thumbnail($id, 'large'); // Large resolution
get_the_post_thumbnail($id, array(100,100) ); // Other resolutions
Where `$id` is the ID of the current post. You can get it via `get_the_ID()`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "post thumbnails, thumbnails"
} |
Wordpress Uploader Editor shows broken image
I have the latest wordpress version installed. When I upload an image in the control panel for a post, I then go to edit it (crop an image for the thumbnail the way I want or rotate or do any kind of editing) and instead it shows a broken image.
The actual images are uploaded, I just can't seem to use the wordpress image editor.
Any ideas why or how to fix? See image below for more detail
!enter image description here | Check the permissions on the file as it sits on the server. Try loading the image URL into a browser and see what error displays. Sometimes I can duplicate the image and reupload and it works. Just some things to try. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "post thumbnails, images"
} |
Widget modifications in a child theme
Can I modify widgets in a child theme? When I change the footer, I don't need extra steps -- it just works. What about widgets?
Example: A widget of a theme I am using makes use of google maps. I'd like to add some options to google maps options array.
My idea is to just copy the widget to the appropriate directory in the child theme and add those lines. Will that work as expected? | Widget are not part of hierarchical parent/child theme relation, so you would need to follow more generic development process:
1. Optionally disable widget registration in parent theme (if possible to do cleanly - with hooks or otherwise).
2. Extend (as in widget's PHP class) or fork (copy and modify the code) widget in child theme.
3. Register your version in child theme. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "widgets, child theme"
} |
How can I run custom function when post status is changed?
I can hook custom function to each of `trash_post`, `edit_post`, `private_to_publish` etc. to meet some of my requirements, but I need also to check for more possible transitions like _'pending to draft'_ , _'private to draft'_ and so on.
Something similar to this inexistent function:
if( post_status_changed($post_id) ) {
my_custom_function();
} | See this Codex page. In general the hook is `{old_status}_to_{new_status}`. (Untested) but in your case, the hook would be `pending_to_draft`:
add_action('pending_to_draft','wpse45803_pending_to_draft');
function wpse45803_pending_to_draft($post){
//Do something
}
You might want to look up the `wp_transition_post_status` function. You could also use the hook: `transition_post_status`
add_action('transition_post_status','wpse45803_transition_post_status',10,3);
function wpse45803_transition_post_status($new_status,$old_status,$post){
//Do something
} | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 5,
"tags": "post status"
} |
Disable h1 and h2 from rich text editor combobox
In the Wordpress control panel, when writing a new post, I would like to disable the Header 1 and Header 2 from the text formatting combobox, because I already use them on my theme (h1 for blog name and h2 for post titles), and would like to keep all headers inside a post with h3 or higher. Is that possible?
It doesn't matter for the case if the code can be edited in the HTML view. Also, I don't want to edit Wordpress internal files, so a hack for functions.php or a plugin would be great for this task, in order to preserve this change across future updates.
Thank you! | you can change lots of things about the tinyMCE editor at the tiny_mce_before_init filter.
<
the following will restrict your blockformats to p,h3,h4 and blockquote
function wpa_45815($arr){
$arr['theme_advanced_blockformats'] = 'p,h3,h4,blockquote';
return $arr;
}
add_filter('tiny_mce_before_init', 'wpa_45815');
**EDIT for WordPress 3.9** see link
function wpa_45815($arr){
$arr['block_formats'] = 'Paragraph=p;Heading 3=h3;Heading 4=h4';
return $arr;
}
add_filter('tiny_mce_before_init', 'wpa_45815'); | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 7,
"tags": "headers, visual editor"
} |
Custom paging function
I use this code for my custom paging :
global $wpdb, $table_prefix, $current_user;
get_currentuserinfo();
$umail = $current_user->user_email;
$paged = $wpdb->get_results("SELECT * FROM {$table_prefix}comments WHERE comment_author_email = '$umail'");
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$pages = COUNT($paged);
$pages = ceil($pages / 2);
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $querystring .= "$key=$value&";
}
// Pagination
for ($i = 1; $i <= $pages; $i++) {
echo "<a " . ($i == $page ? "class=\"selected\" " : "");
echo "href=\"?{$querystring}page=$i";
echo "\">$i</a> ";
}
This code paginate my comments look like this : 1 2 3 4 5 6 7 8 9 10 11
How can change code to get paginate look like this: 1 2 3 ... 11
Thanks for any help. | Instead of the loop at the bottom, use WordPress's `paginate_links()`:
$pagination = paginate_links(array(
'total' => $pages,
'current' => $page
));
echo $pagination;
You can play around with some of < to get the appearance the way you want. Specifically, the `end_size` and `mid_size` will help you to determine the number of page numbers that show, as in your example (1 2 3 ... 11).
If you want something _really_ powerful, you can check out my Boone's Pagination plugin: < (shameless plug!), though it may be too much for your use case :) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "pagination"
} |
Add category to my get_post query
I am using this Query to pull in the latest 3 post
<?php
$query = 'posts_per_page=3';
$queryObject = new WP_Query($query);
// The Loop...
if ($queryObject->have_posts()) {
while ($queryObject->have_posts()) {
$queryObject->the_post();
the_title();
the_content();
comments_template();
}
}
wp_reset_postdata();
?>
I need to add from category 1
I tried adding
query_posts($query_string . '&cat=-3');
at the top of the query, it works but the formatting is not the same and the comment box is missing.
I am using this query in a tabbing plugin and is the only query that pulls in the comment box that works in a tabbing plugin that I have found, so I am trying to get this particular query to work
Thanks for any help | Did you try
$query = 'posts_per_page=3&cat=3';
? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
Getting rid of files not used by latest upgrade
After doing a Wordpress upgrade I notice that there are some files that have an old creation date. Am I safe to delete these on the assumption that they were part of the previous release and so aren't needed for the latest release?
I've used windiff to compare two different downloaded releases (i.e. not my live site) and I can spot files that were in the old, but not in the new, but it would be easier to get rid of the old ones if the answer to my question above was "yes".
For example, comparing 3.2.1 with 3.3.1 there are 80 files in 3.2.1 not present in 3.3.1. Here are a few:
* wp-admin\css\login-rtl.css
* wp-admin\css\login.css
* wp-admin\css\ms.css
* wp-admin\css\nav-menu-rtl.css | For several versions already core updates are partial (differential). Only changed files are downloaded and overwritten so it is not safe to assume that those that weren't are not used.
However, you can compare downloads of two full releases to see which file aren't used any more. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "upgrade"
} |
How to remove ( 0, 0 ) from forum page in bbpress
I would like to remove trailing (0, 0) from the /forums page (forums being the 'forums base') in bbpress. The site is also using buddypress and bbpress got installed as a part of 'group forums'.
Here's how the /forums page looks like at the moment:
General Forums
General (0, 0),
Methodology (0, 0),
Implementation (0, 0),
Tools (0, 0),
Training (0, 0),
New to Lean and Six Sigma (0, 0),
The Water Cooler (0, 0) | From my understanding, these are produced by the function `bbp_list_forums()`, as called in the template file `bbpress/loop-single-forum.php`. You should be able to copy that template into your theme and change the call to `bbp_list_forums()` as follows:
`<?php bbp_list_forums( array( 'show_topic_count' => false, 'show_reply_count' => false ) ) ?>`
See bbPress's inline docs for `bbp_list_forums()` here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "buddypress, bbpress"
} |
Proper use of wp_enqeue_style
I have the following code in my functions.php file. It works, but I am wondering if this is best practice for including styles in wordpress. Also do I need to register the style with wp_reister_style, since it works without and why do I need to do so?
<?php
function mrskitson_load_styles(){
if (!is_admin()){
wp_register_style('main', get_template_directory_uri() . '/style.css');
wp_enqueue_style('main', get_template_directory_uri() . '/style.css');
}//if not admin ends
}//function mrskitson_load_styles ends
add_action('get_header', 'mrskitson_load_styles');
?> | Two problems:
1. You only need to provide the script path _once_ , _either_ in the `wp_register_style()` call, _or_ in the `wp_enqueue_style()` call, but not _both_. (In fact, in this context, it would be fine to omit the `wp_register_style()` call entirely, and just use the `wp_enqueue_style()` call.)
2. You're hooking into the _wrong action_. Try hooking into `wp_enqueue_scripots` instead of into `get_header`. (Note: this will require the Theme to include a call to `<?php wp_head(); ?>` in the document head - but it should be doing so, anyway.)
Other considerations:
* For custom styles/scripts, I would recommend _prefixing_ the style slug; e.g. change `main` to `srskitson-main`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp enqueue style"
} |
How to eliminate custom posts where the "date" value is expired?
I have this code calling a list of custom post events. It calls them in the right order, but when the event is passed, it stil displays the event. Any ideas what's wrong with the code?
$args2 = array(
"post_type" => "gig",
"meta_key" => "_gigswhen", // Change to the meta key you want to sort by
"meta_query" => array(
array(
"meta_key" => "_gigswhen",
"value" => date(),
"compare" => ">=",
),
),
"orderby" => "meta_value_num", // This stays as 'meta_value' or 'meta_value_num' (str sorting or numeric sorting)
"order" => "ASC"
);
The date in "_gigswhen" is stored as strtotime (unix timecode) | You can't use `date()` with no parameters. See <
Try this for your `meta_query` argument:
'meta_query' => array(
array(
'key' => '_gigswhen',
'value' => time()
'compare' => '<'
)
) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Move wordpress sidebar on homepage up to new position
This should be a simple task, however I am having no such luck. I am using a theme that has a homepage slider which spans across the entire content area. I have been asked to reduce the size of the slider and move the sidebar up next to it. I've attempted to call the sidebar in different and seemingly logical locations but the page breaks.
Any help would be much appreciated. index.php code here: < Style sheet and site URL in comments if needed. | The best way is to move `<div id="side">` outside of `<div id="content">`, so that you can properly position it next to the slider (`<div id="lof-container">`). Alternatively, you could do it with
#maincontent { overflow: visible; }
#side { margin-top: -300px; }
though this is pretty hackish. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, themes, register sidebar"
} |
Easiest way to simulate WordPress's URL resolution to retrieve post ID, etc?
I'm curious if it is possible, in a plugin/custom code, to take an URL that has been generated by the currently running WordPress site & parse it to retrieve the $blog_id and $post_id?
ie. taking a string like "myblog.mysite.com/2012/03/16/whatever/" and determining that this is post #6 ("whatever") on blog #2 ("myblog").
I realize that I can probably strip the URL and parse the domain myself, but I hope that there might be recommended WordPress methods exposed to make this more robust across URL formats. | As Weston mentioned, if you're within WordPress and you know what blog the URL came from, then ask WordPress for the blog ID.
But if you're really, really sure there's no better method in this case than parsing a URL, then here you go:
$url = '
$domain = parse_url( $url, PHP_URL_HOST );
// This could be dynamic but good enough for now
$subdomain = str_replace( '.mysite.com', '', $domain );
// Never use $blog_id for anything, you'll break tons of things
$parsed_blog_id = get_id_from_blogname( $subdomain );
// url_to_postid() only works for the current blog
switch_to_blog( $parsed_blog_id );
$post_id = url_to_postid( $url );
restore_current_blog();
Reference material:
<
< | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "urls, slug"
} |
Show posts of category in a page
I would like to be able to display all the posts in a certain category on a page so that all posts are on that one page and there is no pagination.
If possible, I would also like to display a short preview of the posts - all posts will have a thumbnail and a short paragraph at the start.
I've tried various different plugins, but so far none of the one's that I have found do the job.
Does anybody know of a plugin or a way to do this? Alternatively, modifying the default category pages so there is no pagination is an option if all else fails... | I found a plugin-solution eventually to the my second option. I now use Posts per cat and set it to some silly number so that all of the posts in the category display on one page; it turns out that's all I needed!
Thanks and Regards | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "categories, pagination, pages"
} |
post_title is empty on global $post object
My plugin uses publish_post hook to get the post data and do some processing:
add_action('publish_post', 'publish_post');
function publish_post($post_id) {
global $post, $blog_id;
$author = get_userdata ($post->post_author);
$title = $post->post_title;
//some processing here...
}
I notice that for a new post, $title is always blank, while all other fields are available. If I publish the post again (update), then the title becomes available.
**Edit**
I printed out the $post variable and notice that that the post_status is draft:
[post_title] =>
[post_excerpt] =>
[post_status] => draft
So it seems the $post variable contains what was loaded from the database, but not what is currently on the screen. How should I get the $post that reflects what is currently on the screen? Is there a hook that fires after a post is saved to the database? | This hook is called like this:
do_action("{$new_status}_{$post->post_type}", $post->ID, $post);
My guess is that you should be using data passed as second `$post` argument, rather than global.
So:
add_action('publish_post', 'publish_post', 10, 2 );
function publish_post($post_id, $post) {
// stuff | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development"
} |
Show validation warning if no Excerpt is added
Is it possible to display a warning in the admin section when posting if the excerpt section hasn't been filled out to stop a post being published without an excerpt?
Does anyone know of a plugin that has this facility? | Writing your own plugin will help you understand WordPress better, subsequently enjoying it even more, beside you look like you are quite capable with some tiny bit of PHP, no?
When saving a post, the `save_post` hook is pulled on. This passes along the `$post_ID` and the `$post` variables, containing everything you need to check for `post_excerpt` (like `if ( strlen( $post->post_excerpt ) < 10 ) ...`).
If you want to explicitly do this only when a post is published you can hook to `{$old_status}_to_{$new_status}` hook.
To show a nice message or warning, tap into the `post_updated_messages` hook. You can alter the `$_GET['message']` variable inside the `redirect_post_location` filter.
Alternatively, you can display the warning on the page at all times just by looking at the `$post->post_excerpt` property. Style it as an alert or use jQuery to remove the publish button altogether until the field is filled. Lots of options, depends on how far you're willing to take it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "excerpt"
} |
wp_insert_link not working
Im using this code to insert links into my blog:
$linkdata = array(
'link_name' => $title,
'link_url' => $url,
'link_catetory' => 3, // my cat id
);
$link_id = wp_insert_link( $linkdata );
Links are inserted, but not in the correct category, I missed something? | I would guess `link_catetory` should be `link_category`. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, links, link category"
} |
How do I get posts that have a thumbnail in WP_Query?
I want to grab the 5 most recent posts that have thumbnails. | You should be able to call posts with a featured image with the following code:
$thumbs = array(
'posts_per_page' => 5,
'meta_query' => array(array('key' => '_thumbnail_id'))
);
$query = new WP_Query($thumbs);
The code checks each post for the custom field _thumbnail_id, which is where the thumbnail image is stored. | stackexchange-wordpress | {
"answer_score": 30,
"question_score": 12,
"tags": "wp query"
} |
Problem with permissions in wp-content/plugins
I have a WP installation on my local machine and trying to get my hands dirty with plugins. I wish to clone a project from github which has this plugin code. However, i dont have the permissions inside plugins to do this as a normal user without su priveleges. (of course i can become root and do this but i dont think thats the way it should be).
Then by default the folders in a WP installation have group set to "tape", which appears strange to me.
What exactly should be the right permissions for the internal folders on a local WP installation? | Best thing to do is check the WP docs themselves for correct file/folder permissions and how to change them, if needed: <
> Typically, all files should be owned by your user (ftp) account on your web server, and should be writable by that account. On shared hosts, files should never be owned by the web server process itself (sometimes this is www, or apache, or nobody user).
Is "tape" a local user name? Or FTP name?
Depending on what kind of system you're using - a local install of apache, php and mysql - or a stack like Bitnami, XAMPP or MAMP, there may be slightly different owners and groups for folders and users. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, security, permissions"
} |
What problems maybe happen if I remove "wp-" prefix from wordpress folders and files?
I want to hide wordpress signs from my site. So I don't want other people know that I built the website via WordPress. So I decided to remove `wp-` prefixes from all wordpress folders and files. And I also removed `wp-` prefixes from file contents with Notepad++. So my question is what problems maybe happen if I removed `wp-` prefixes ?
Thanks in advance. | Editing core is extremely bad practice. At best you will break updates, at worst random thing would be completely broken all over.
See Steps to Take to Hide the Fact a Site is Using WordPress? for better alternatives. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "core, core modifications"
} |
Disable Comments Feed
I am working on a private site where the comments need to be hidden. I know how to remove the comments feed from the header, but can anyone give me some instructions on how to disable the comments feed altogether. Because all you need to do is add /feed/ to the single post and then you can see the comments feed.
I tried creating feed-atom-comments.php, and feed-rss2-comments.php, and that still did not work. | Something like this should work.
function wpse45941_disable_feed( $comments ) {
if( $comments ) {
wp_die( 'No feed available' );
}
}
add_action('do_feed', 'wpse45941_disable_feed',1 );
add_action('do_feed_rdf', 'wpse45941_disable_feed',1 );
add_action('do_feed_rss', 'wpse45941_disable_feed',1 );
add_action('do_feed_rss2', 'wpse45941_disable_feed',1 );
add_action('do_feed_atom', 'wpse45941_disable_feed',1 );
Note: I haven't tested that at all, I just wrote it right into the answer box. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "comments, feed"
} |
Using wp-postratings to rate user on profile pages
I'm using wp-postratings on my site and I want to include it on the buddypress profiles of my members so other users can rate them. I place the function on the profile page but it doesn't do anything when a rating is clicked. Any ideas on what I can add to make it work? | It's likely that it will not be as easy as adding something small to make it work.
Plugins like WP-Postratings store their data on a post-by-post basis. But BP members are not posts. So you would have to intercept the way in which the plugin stores its ratings data natively, and save it to users instead.
Moreover, you'll have to modify/extend the markup and JavaScript created by WP-Postratings so that the current "item" being rated on is the member's user id, rather than the post id. Then, because the rating happens via AJAX, you'll have to make sure that the new id is sent properly in the request, and that the server-side handler is set up to expect member data rather than post data. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "buddypress, profiles, plugin wp postratings"
} |
Setting image upload absolute path?
In anticipation of a major upgrade, I moved the webroot from `site_v1` to `site_v2`. The public url for the WP 3.3.1 install is still example.com/ (no change). I did a tar copy from the /site_v1 dir to the new /site_v2 dir.
The WP installation is working well from its new Linux path of /site_v2 instead of site_v1. All pre-existing images continue to work fine etc.
**The Problem** is that when new image files are uploaded using either the flash or classic uploader, the files themselves are put into /site_v1/wp-content/uploads/2012/03 instead of the correct /site_v2/wp-content/uploads/2012/03 location.
How do I change the upload file location? | Sorry if you have tried this already, but I go for the simplest answer first ;)
In dashboard, Settings -> Media -> Uploading Files section to set path. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "uploads"
} |
Remove the number of posts displayed in wp_list_categories()
When I use wp_list_categories(), it results in the number of posts in a category being shown, how do I hide the number?
For example: I have xyz category, it has 3 posts, the result will be:
xyz(3) | By default `wp_list_categories()` doesn't show post count, because `show_count` is set to `false`, check arguments passed into `wp_list_categories()`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
Wordpress Custom Post Type Children Template
I have created a hierarchical custom post type in wordpress called "films." It is hierarchical so it can have children elements.
When a "film" is clicked, wordpress automatically uses the template called 'single-films.php'. That is great, but I wish to use a different template when one of the film's children pages is clicked. For instance, a child of a film might be "press." When that film's press link is clicked, I want it to use a different template than single-films.php.
I was hoping there is some way I can use a template like single-children-films.php. Any ideas how I can change a hierarchical custom post type's children template? | If, from within `single-films.php` you filter based on the parent post you should have little issue with this. For example:
if( $post->post_parent != 0 ) {
// not top level
} else {
// top level page
}
If you need to know how deep the page is, that's a different matter, but that's also doable (unfortunately it means you need to query the database though). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, templates, hierarchical"
} |
wp_head function outputs after <head>
I have a function in my functions file where i output Google Analytics code.
function mytheme_trackingcode(){
$mytheme_option = mytheme_get_global_options();
$tracking_code = $mytheme_option['tracking_code_head'];
if($tracking_code){
echo '$tracking_code';
}
}
add_action('wp_head', 'mytheme_trackingcode');
The problem is that the output comes right after the tag. I'm not sure what the problem is? wp_head is placed last in head-section. | `'$tracking_code'` ist just a string. It closes `<head>` automatically. So, no, it doesn’t come after the `head`, you just failed to use **source view**. Firebug and similar tools show just the rendered DOM, that’s not good enough.
Fix: `echo $tracking_code;`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp head"
} |
disable reply comments on depth equals 2
Using budypress and I'm trying to disable comments on comments' comment, meaning depth 2.
The structure would go like this.
Main Comment. Someone made a comment <\-- Reply is possible Another person made a comment of this reply <\-- No1 can comment this
Any ideas?
Thanks in advanced. | NVM, shame on me, I just realized I can control the depth in the wp options.
Settings -> Discussion -> Enable threaded (nested) comments 2 depth | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
Data validation for inline javascript
I try to save inline javascript(Google analytics code) in wp-options table. But i can't figure out what validation function i shall use.
I have tried esc_js when saving to the database. But i can't figure out what to use when i shall echo it in the head section. | You can use `addslashes()` and `stripslashes()` to prepare any data for database entry. These are native PHP functions, not wordpress functions, so they do not necessarily need to be hooked anywhere specific in the wordpress load to work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp head, sanitization"
} |
Trying to output content from page, works locally but not online
I am using the following code, to output the content from a page with the id of two. This is in my custom template file which is selected in the page. It works fine locally but online it does not work, it outputs nothing, the id is based of this url ` What might I do to diagnose this problem.
<?php $my_query = new WP_Query('page_id=2'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?> | have you tried get_page() ?
$page_id = 123; // 123 should be replaced with a specific Page's id from your site,
$page = get_page( $page_id ); // You must pass in a variable to the get_page function.
echo '<h3>'. $page->post_title .'</h3>';// echo the page title
echo apply_filters('the_content', $page->post_content); // Get Content and retain Wordpress filters such as paragraph tags.
<
don't forget to make sure you change the $page_id to match your live version | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
Lost formatting after saving
I make basic formatting to the text in visual editor. When saving, everything got lost, formatting, spaces, paragraph.... everything got inline...
I will go crazy !... why it's doing that ?.. i can make testing as request to gt out of this problem.. thanks in advance
the DB and WP got reinstalled, and is hosted on hostpapa. I have others client on iweb and those work fine. I have no choice now, to make it work on hostpapa, the migration to iweb will be the LAST thing of last resort !
i am using qtranslate, wich can be the plugin the bug the editor | After a lot of research (2 day) i finally found a plaster... it's not a fix, but it make the editor work for most of the work. Here is the code to add to function.php of the theme:
function cbnet_tinymce_config( $init ) {
$init['remove_linebreaks'] = false;
$init['convert_newlines_to_brs'] = true;
$init['remove_redundant_brs'] = false;
return $init;
}
add_filter('tiny_mce_before_init', 'cbnet_tinymce_config');
and here is where i found it : HERE | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "visual editor, formatting"
} |
Comment time is same as the post time
Here is my comments.php: <
The problem is that the threaded comment (the reply) showing my post date instead if the comment date. I checked in the database and it looks fine there. The date is the same but the time is good(11:13)
Example: <
In my comments.php i can't find my threaded comment syntax, its probably in the comment_text() function, right? How can i edit that to make this problem disappear? | Try to use the wp_list_comments function:
<
It allows you to control the aspect of every comment, also the replies. Then, you define a callback function, which will be called when Wordpress creates each comment.
Your callback needs to start like this:
function commnents_callback($comment, $args, $depth) {
$GLOBALS['comment'] = $comment;
global $post;
// your HTML + PHP comment creation code here
}
Then, you can create the comments by using this code:
<?php if( $comments ): ?>
<ul>
<?php wp_list_comments('type=comment&callback=commnents_callback'); ?>
</ul>
<?php endif; ?>
Using this, you can control the creation of every comment. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date time, date, comments"
} |
Display all search results
Is there a way to display all the search results on the `search.php`? Actually it is displaying only 10 results (as set in `WordPress settings > general`). | The quick and dirty way to do it would be to use `query_posts` again, doubling the number of database calls.
<?php if (have_posts()) : ?>
<?php query_posts('showposts=999'); ?>
Better would be to add this to `functions.php`, altering the original query before it is executed:
function change_wp_search_size($query) {
if ( $query->is_search ) // Make sure it is a search page
$query->query_vars['posts_per_page'] = 10; // Change 10 to the number of posts you would like to show
return $query; // Return our modified query variables
}
add_filter('pre_get_posts', 'change_wp_search_size'); // Hook our custom function onto the request filter
If you want to show an unlimited amount of posts, use `-1`. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "posts, search, options"
} |
How can I get multisite primary blog (url or path) for current user?
In a multisite setup, when users are visiting a blog/site that there are not a member, I would like to display a link to "HOME" that takes them to their "primary" blog.
I know how to determine if a user is or is not a member of a site with the is_current_blog_user() function. The part I am having a problem with is correctly setting the url/path of the "HOME" link to the current users "primary" blog.
Hypothetical Example:
<a href="<?php this_is_the_path_to_users_primary_blog();?>">HOME</a>
I have found the get_active_blog_for_user ( function, and this seems to be a good place to start. But I feel as though I must be missing something, and this must be easier than I am making it. | Indeed, `get_active_blog_for_user` should work.
$blog = get_active_blog_for_user( get_current_user_id() );
$blog_url = $blog->domain... /* or $blog->path, together with $blog->siteurl */
Alternatively:
$blog_id = get_active_blog_for_user( get_current_user_id() )->blog_id;
// note: changed "->userblog_id" to "->blog_id" in row above to make it work.
switch_to_blog( $blog_id ); /* switch context */
$home_url = home_url();
restore_current_blog(); /* back */ | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "multisite, users, user access, homepage"
} |
Add contact form
I want to add contact form to my page. I found < article where (see below) there is button for adding contact form but I don't have this in my Wordpress installation.
!enter image description here
Do I have to add some plugin or what? I use wordpress 3.3.1. | If you are self-hosted, you won't have that button, as that is for Wordpress sites hosted by wordpress.COM
See The difference between WordPress.com, WordPress, and WordPress.org
Search for plugins for self-hosted Wordpress:
< is very popular. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "forms, contact"
} |
How to add inline css code with background image in page html code?
I want to add inline css code inside a page of my blog. This css code calls an image as background of a div.
Is this possible? and how to do that?
I have tried to add the image as a Media resource, and got a URL for it, but using this URL does not seem to work.
Example of code that I paste to my page html:
<p><a href=" style="width: 90%;
font-family: Helvetica, Arial, sans-serif;
background: #0e710d url( 0 0 repeat-x;
font-size: 1.6em;
">
Click here »</a></p> | cant you just give that link a class? why touch your template files?..
anyhow i see no reason why you can't to that... the css should work..
The only change i would do when editing a template file is
using php to get the folder url (where you image is) like so:
<style type="text/css">
.specialLink a {
width: 90%;
font-family: Helvetica, Arial, sans-serif;
background: #0e710d url("<?php get_bloginfo('url'); ?>/wp-content/uploads/2012/03/image.png") repeat-x 0 0;
font-size: 1.6em;
}
</style>
<p class="specialLink"><a href=" here »</a></p>
**Again... i reccomend you use your style.css to load that css and not in
template files.. if you need it just for a specific page say so... i have
a better solution for that.**
Hope this helps, Sagive. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "css"
} |
Regenerate Slugs From Title of Posts
is it possible to regenerate the slugs programmatically after changing the titles of the post? Numerous post titles were updated and the slug was not updated with the title so I need to regenerate all these slugs. | Yes, it is possible.
Sample code, has to be tested and refined:
// get all posts
$posts = get_posts( array ( 'numberposts' => -1 ) );
foreach ( $posts as $post )
{
// check the slug and run an update if necessary
$new_slug = sanitize_title( $post->post_title );
if ( $post->post_name != $new_slug )
{
wp_update_post(
array (
'ID' => $post->ID,
'post_name' => $new_slug
)
);
}
}
I just made this up, there are probably some errors and egde cases, but it should give you an idea. Also, this may take a while, so it could be useful to split the update into smaller chunks. | stackexchange-wordpress | {
"answer_score": 25,
"question_score": 16,
"tags": "get posts, slug"
} |
Ajax requests with different WordPress Address and Site Address setup
I have a user using my plugin with the following wp setup
WordPress Address (URL)
Site Address (URL)
I am using admin_url( 'admin-ajax.php' ) to pull the ajax url, which returns
When doing ajax requests from a page on < it looks like the "same origin policy" is in effect and the requests fail. Any suggestions on how to fix this issue? | Depending on how you're mapping `somewebsite.com`, you can probably just define `ajaxurl` differently:
`var ajaxurl = '
If you need something more generalizable, you could filter `admin_url`, sniff out whether it's asking for `admin-ajax.php`, and if so, then rewrite it using `home_url()` or something like that.
Getting cross-domain ajax to work is possible (with a proxy approach, for instance) but it's best to avoid it if at all possible. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "ajax"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.