INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
use post meta in add_meta_boxes action
Is there any way to use get_post_meta within a function called by the add_meta_boxes action hook?
I only want to display the meta box if a specific post meta matches a regex, but so far, I have not idea how to do so. | You can not put condition in callback function as it will display the meta box without the HTML. Better you can wrap `add_meta_box()` in `if` condition.
If you are on post edit screen you can get the post id in this way.
$post_id = false;
if (!empty($_POST['post_ID'])) {
$post_id = $_POST['post_ID'];
} else if (!empty($_GET['post'])) {
$post_id = $_GET['post'];
}
if (get_post_meta($post_id, 'yourKey', true)) {
add_meta_box($id, $title, $callback, $screen, $context, $priority, $callback_args);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "metabox, post meta"
} |
Are database queries created using WordPress filters protected from SQL injection?
I'm using the WordPress 'posts_where' filter (< to alter my queries as below:
function filter_my_search($where=''){
global $wpdb;
if(isset($_GET['q'])) {
$where .= 'AND (((' . $wpdb->posts . '.post_title LIKE "%'.$_GET["q"].'%") OR (' . $wpdb->posts . '.post_content LIKE "%'.$_GET["q"].'%")))';
}
return $where;
}
add_filter('posts_where', 'filter_my_search');
So a query is being run, and I'm intercepting the where clause, and adding an extra condition. Would that code be susceptible to SQL injection? | No! WordPress will **not** protect against SQL injection in this case. You need to do so yourself, using `$wpdb->esc_like` and `$wpdb->prepare`:
if ( isset( $_GET['q'] ) ) {
// WordPress forces magic quotes (god knows why), unslash it
$value = wp_unslash( ( string ) $_GET['q'] );
// Escape like wildcards so that MySQL interprets them as literals
$value = $wpdb->esc_like( $value );
// Create our "true" like query
$value = "%$value%";
// Now inject it safely
$where .= $wpdb->prepare(
" AND ( ( $wpdb->posts.post_title LIKE %s ) OR ( $wpdb->posts.post_content LIKE %s ) )",
$value,
$value
);
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "query, mysql, sql"
} |
Insert media while posting is not working with new wordpress update
Insert media while editing or adding post is not working since the 4.1.2 update. But I can upload media through media manager itself.
I didn't change anything in the site today, only the automatic update to wordpress 4.1.2. But since then I found this issue.
And the funny thing is I have two instance of same wordpress site and both of them updated in the morning. But one is working as normal, but one is not working.
When I debug it with console I saw that the working instance is using `POST asynce-upload.php` while other one using `POST admin-ajax.php` to upload media.
Anyone has an idea about that ? | I disabled the `post thumbnail editor` plugin, then everything started to work again as normal.
But for the general advise for similar kind of issue is, disable your plugins one by one and test. Then you can find the plugin which is not compatible with wordpress update. So that you can disable that plugin at lease until it is giving new update.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, media, media library"
} |
What function publishes a post when you click the publish button?
I'm trying to track down an issue with a plugin. In vanilla WP when you are on the post edit screen (/wp-admin/post.php) what function is getting called to change the post status from draft to publish?
I've looked in that post.php and there is nothing that I'm seeing do it. I'm thinking that it may be some kind of AJAX call and I tried pausing execution to see what's happening when you click that button but I couldn't find anything. | Normally, posts are published by the `wp_insert_post()` function. Essentially, the `post_status` is changed from draft to publish. Nothing more to it than that, really.
There is also the `wp_publish_post()` function, which is really only used for scheduled posts. It does the basic job of transitioning a post from "future" to "publish", and also calls the same various action hooks that `wp_insert_post()` would normally call, so that plugins and other functions which take actions on publishing of posts behave correctly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, post status"
} |
Shared table across network
Im currently creating a plugin that will read an xml file and import the data into 4 tables on a wordpress multisite. the tables are rather large, with ALOT of columns, so the post table is not suitable for this task. Every "blog" on the network needs to be able to access the data from this table.
I have tried creating the tables by following the codex instructions here using the dbDelta function: <
but on a multisite this creates a set of tables for each "blog" in the network. This is redundant as the data would be identical across all the different table sets.
I have been googling around but can't really find a WordPress-way of doing this.
Does anyone have ideas as yo how this is best achieved? When the plugin is activated network-wide, it needs to create a single set of tables to be accessed from all the blogs in the network | Use `$wpdb->base_prefix . 'table_name'` as a table name when you want to create a table for the whole network, or when you want to run queries on it.
`$wpdb->base_prefix` is always the prefix for the current network’s main table. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "multisite, database"
} |
Custom JS on a specific page
So, I have the following custom JavaScript in a page. (Written exactly the way it shows, except the img src)
<script src="
<script>
jQuery("#first").click(function(){
jQuery("#second").trigger('click');
return false;
});
</script>
<a id="first" href="#"> <img src="demo"> </a>
So the by clicking "first" button, it will trigger "Click" on the second button. The functionality itself works (ie. the "second" button is triggered)
However all other JavaScript functions are not working.
I am guessing adding a custom JavaScript file directly into the page is not the best way.
I see that there are some plugins to add JavaScript in a post/page, but I am trying to avoid any unnecessary plugins.
What would be the best way to add the custom JavaScript without affecting other JavaScript functions? What am I doing wrong?
Thanks | First of all, you should declare your scripts using wp_enque_script.
Second, jQuery is loaded automatically in WordPress and is set to no conflict mode. See the documentation for how to link a script that depends on jQuery.
Lastly, if you want it to appear on just one page you have two options
1. In your `functions.php` file add a custom field to either enable this script on that page.
2. Manually insert it on a given page, again via `functions.php` To target only the home page `is_home()` but of course you could just reference a page by it's page_id like this `get_page( $page_id )`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript"
} |
How to list all names and descriptions of a custom taxonomy
I have a custom taxonomy (toolkit-sections) inside a custom post type (toolkit-tools) and I'm looking to just list the taxonomy names and descriptions from toolkit-sections on a homepage.
I don't want to list any posts from inside these taxonomies, I just want to show what the taxonomies are called and what their descriptions are.
Do you know how to do this? I really, really would appreciate any help! | You can use get_terms.
In your case, something like this ought to get you started:
$term_list = get_terms( 'taxonomy_name', 'hide_empty=0&orderby=name' );
foreach( $term_list as $term ) {
echo "<li>" . $term->name . $term->description . "</li>";
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, taxonomy, customization, description"
} |
Prevent CF7 attachment from being deleted
I am using a contact form 7 plugin for an inquiry form and sending the visitor 2 local files attached to the reply email. The function I used is this:
function my_dynamic_attachments($cf7)
{
$submission = WPCF7_Submission::get_instance();
$submission->add_uploaded_file('toe', get_template_directory().'/attachment1.pdf');
$submission->add_uploaded_file('ep', get_template_directory().'/attachment2.pdf');
}
add_action( 'wpcf7_before_send_mail', 'my_dynamic_attachments', 10 );
The problem I am facing is that the attachments are deleted from the server after the email is sent, thus they are not available for the next visitor. Is there any way to prevent this from happening?
Thank you in advance! | Looking at `submit()` in `WPCF7_Submission` we see a call to `remove_uploaded_files()` which has no filter to stop it. So apparently what you are trying to do isn't meant to be done by the author of CF7.
So apart from getting the author to include a hook there the only way I see is that you generate your file and then create a copy before adding it to the form submission so your original file stays. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugin contact form 7"
} |
Get the number of posts in a named category, outside the loop
I've managed to do this from a `single.php` file, inside the loop, but now I need to do it from another page.
I need to find out how many live posts are in category named `every story` (slug is `everystory`). I am not inside the loop.
I just need the number, I don't need to output anything except the number. E.g `8`
I have tried searching for a way to gather category data just via the `category_name` (could be name, or could be slug, could even be by category `ID`) but everything I've found so far refers to using a specific `$post` var and finding it's category which isn't what I want to do.
Here is the example of what I used on the `single` post page:
$category = get_the_category();
$counter = $category[0]->category_count; | I'm a bit unsure of you are actually asking, so apologies if I understood it wrong.
You can use `get_category()` to get the category object and then just simply echo the `$count` property value
$cat_count = get_category( 'ID OR ROW OBJECT' );
echo $cat_count->count; | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "categories"
} |
Downloading Generated XML File
I'm making a Widget which presents users with categories as drop down list. When user selects category and press download, I want to get all posts under category and download them. I have faced a problem on downloading. I do something like
$xml = ''; //generated XML with Simple XML
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="text.xml"');
echo $xml->asXML();
I get headers already sent. So I added buffering to init with code:
add_action('init', 'do_output_buffer');
function do_output_buffer() {
ob_start();
}
and in my `MY_Widget::widget()` I add the code `echo ob_get_clean();` after `echo $xml->asXML();` explained above. Here it works except it exports whole page (with my XML) as single XML file.
Is there a way to download file without including whole page? | I just had to clean buffer and then do my stuffs and call exit
ob_clean(); //clear buffer
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="text.xml"');
echo $xml->asXML();
exit(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, widgets"
} |
Removing get_template_part in child theme
Parent Theme loads some template files in its functions.php as follows:
get_template_part ('lib/login/register.php');
I want to remove this file in child theme and include my custom php templates.
How can I remove get_template_part function from parent theme.
Thanks | Copy the file to your child theme,
In your child theme, create a template and name it what ever you want, e.g `content-child.php`
Now you can replace `lib/login/register.php` with your new template:
<?php get_template_part( 'content-child', get_post_format() ); ?>
It should work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, child theme, get template part, parent theme"
} |
When using W3 Total Cache should I remove my enqueues from functions.php
I am using W3 Total Cache, but when adding the stylesheets and scripts to cache I am not entirely sure whether I should remove those scripts from my functions.php enqueue list or not.
Also a small additional question. Is it a good idea to add Google Fonts to the cache _and_ minify them? | There is no need to deque CSS files and JS files from functions.php as W3Total Cache can be configured to combine all CSS files into one and later it in minified.However you must keep in mind that all CSS and JS files are combined serially(one after another , so you load them as per your theme requirements) and then minified into one.
Google fonts are not served from your own server,so, you can't really minify and concatenate it.Also, Googles font servers are probably faster than if you'd host the fonts yourself. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin w3 total cache"
} |
What is this HTTP_REFERRER "WordPress/4.1.2"
On our website we have huge traffic with same IP and referrer **"WordPress/4.1.2; The log line looks like:
> 62.24.2.2 - - [22/Apr/2015:17:28:15 +0200] "GET /wp-content/uploads/2015/04/randevouz.jpg HTTP/1.0" 200 791898 "-" "WordPress/4.1.2;
The IP and domain xxxx.com are real and I can see the website who doing it, but before block I want to know what this is. | That log entry indicates the someone form that IP is requesting a image file from your site. The referrer "WordPress/4.1.2" indicates that it is probably using WP HTTP API, so the image is not just inserted in HTML (using `<img>` or any other HTML element) but requested server-side. Why? It can not be known with the provided information; maybe the other site is downloading the image to its own server. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "headers, api, http"
} |
Benefits of using Nav Walker?
Are there any benefits to using a nav walker class over iterating through wp_get_nav_menu_items()?
Nav walkers seem very clunky to me and iterating over an array feels easier and more re-usable but it then bypasses the internal menu filters of wordpress that I don't know much about. Will this make my theme incompatible with some plugins?
Best practice advice here would be greatly appreciated. | I would say mostly you see the usage of `wp_nav_menu()`, which does use `wp_get_nav_menu_items()`. You can use `wp_nav_menu()` with the default walker or a custom walker.
To be honest I can't remember the time I did a menu manually, with `wp_get_nav_menu_items()` or something else, and I tend to be lazy, so this is definitely more work.
The Walker Class gives you a lot of possibilities as there is more information available, which definitely is big plus. So whether you should leverage a walker - or otherwise (I'd say) use `wp_nav_menu()` \- is pretty much a question of what you need to achieve, for more complex menus I personally would always go with a walker. Last but not least, walkers are nicely reusable, which is pretty neat and another plus. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "menus, navigation, walker"
} |
Add categorys to custom post type not working
register_post_type("butik", [
"labels" => [
"name" => "Butik",
"singular_name" => "Butik"
],
"show_ui" => true,
'public' => true,
'rewrite' => [
'slug' => 'butik'
],
"supports" => [
"title",
"editor",
"thumbnail"
],
'taxonomies' => array('category')
]);
That's my code for registering the post type and trying to add the taxonomies, but it still aint showing.
Any clues?
Thankyou for your effort! | That is not the way to register a Taxonomy.Please find the code below to register a Taxonomy for a custom post type :-
$args = array(
"label" => "Butik Categories",
"singular_label" => "Butik Category",
'public' => true,
'hierarchical' => true,
'show_ui' => true,
'show_in_nav_menus' => false,
'args' => array( 'orderby' => 'term_order' ),
'rewrite' => false,
'query_var' => true
);
register_taxonomy( 'butik-category', 'butik', $args );
Hope that solves the problem.You can also use plugins like Custom Post Type UI to easily create Custom Post Type.Here is the link :- < Hope that helps :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Genesis / custom template page / setting the page title and meta desc
My WP site is running Genesis. I've just implemented my first custom page template in a child theme. The template runs some PHP and makes some data available to any page based on the template using shortcodes. All is working well, except...
For SEO, I'd like to set several items in the _head_ section - most importantly the page title but also some meta items. I use the Yoast Wordpress SEO and this section is top/tailed with a Yoast comment so perhaps it's taken charge of these fields.
Are there any filters I can use (perhaps with a higher priority than Yoast uses) to set selected _head_ items? | Yoast Support kindly provided me with the following reference:
<
Using the following filters calling my own functions, I was able to change everything in the header based on dynamic content.
add_filter('wpseo_title', 'setPageTitle', 10);
add_filter('wpseo_metadesc', 'setMetaDesc', 10);
add_filter('wpseo_canonical', 'setCanonical', 10);
add_filter('wpseo_opengraph_image', 'setOG_Image', 10);
add_filter('the_title', 'setTitle', 10); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, seo, genesis theme framework, plugin wp seo yoast"
} |
When add_query_arg() is necessary?
considering this code, both solutions seems to work fine. What I don't get is, is there any difference between the two solutions?
general_plugin.php
function add_custom_query_var( $vars ){
$vars[] = "custom_var";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
plugin_part1.php
...
echo '<a href="
...
plugin_part1-fixed.php
...
echo '<a href=" "custom_var", $db_table->db_column).'">text</a>....'
... | The difference is, in "plugin_part1-fixed.php" you wouldn't lose existing args. Consider the url:
Your code in "plugin_part1.php" would output
<a href="
Note, the existing arg "foo" has been lost, the code in "plugin_part1-fixed.php" would output:
<a href="
Note, the existing arg "foo" is still present and your arg has been appended.
Since you don't have any existing args you don't see a difference. That said, using `add_query_arg()` is still best practice since you don't know if you'll have to interact with another plugin that might also be sending args for whatever reason.
Also, please keep in mind that you should always wrap `add_query_arg()` in `esc_url()` to prevent XSS scripting as better explained here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "query"
} |
Custom Behavior when Adding New Custom Post Type in Dashboard
I have a Custom Post Type that I'm doing some custom work for. I want to attach some custom functionality to the post type once it's created but an admin can only trigger the custom action from the dashboard.
**For Example**
You create a new Post of the custom type and after it's created you can go to edit the post and in there you see a button that says "Custom Function" which will run some javascript.
**The Idea**
I need the custom button to run a function in functions.php which will create X amount of entries in a custom table on the mysql database and then return the values. I'll use an input next to the button to decide X's value.
I'll be fine with the php + sql + ajax but I just don't know a non-hack way to get the custom inputs to show up on the edit page. Any ideas? | Add a meta box to your custom post type edit screen to contain your markup. Check the `$pagenow` global to only show it on `post.php`, not `post-new.php`, and check `$current_user` global for administrator role to exclude other user roles.
Also, if you aren't familiar, check out the `$wpdb` class for your queries, and read up on using AJAX in WordPress.
**EDIT** use `get_current_screen` and `current_user_can` rather than dirty, dirty globals, as @TheDeadMedic suggested in comment below. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, customization, custom field"
} |
Pushing Category and Publish Date to Google Analytics
I have found an interesting article about tracking variables with JS based statical system (for example Google Analytics).
The article writes examples like:
_gaq.push('setCustomVar', 3, 'pubDate','YYYYMM',3);
_gaq.push('setCustomVar', 4, 'contCat','[CATEGORY NAME]',3);
_gaq.push('setCustomVar', 5, 'contSubCat','[SUB CATEGORY NAME]',3);
But how can I get the actual value of the pubdate from the PHP environment of Wordpress and write it in the HTML generated code so that it will be really made available to analytics? I hope the question is clear enough. | If you're printing your script inline (i.e. not in an external file), you can use PHP to dynamically output the JavaScript argument:
<script>
_gaq.push( 'setCustomVar', 3, 'pubDate', '<?php the_time( 'Ym' ) ?>', 3 );
</script>
See the PHP manual for date arguments, which will explain why I've used `Ym`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "variables"
} |
Multiple instances of Redux WP Framework
Is it possible to have multiple instances of Redux WP framework? Not subpages, i need multiple separate instances since 10+ subpages with tons of options is really really slow. | Lead dev of Redux here. You sure can! Just be sure to specify a different opt_name as well as a different page_slug and you're golden. Redux was built to do just that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "theme options"
} |
Different read-more link for each custom post type
Trying to make a custom 'read more' link for different custom post types.
Tried this code but does not work as expected. Fairly certain the if/else logic is amiss.
Using a Genesis theme if that makes a difference.
function excerpt_read_more_link($output) {
global $post;
if ($post->post_type = 'speaker')
{
$output .= '<p><a class="speaker-more-link" href="'. get_permalink($post->ID) . '">View Speaker Profile</a></p>';
}
elseif ($post->post_type = 'resources')
{
$output .= '<p><a class="speaker-more-link" href="'. get_permalink($post->ID) . '">More Resource Content</a></p>';
}
else
$read_more_text = 'Read more';
return $output . '<a class="more-link" href="'. get_permalink($post->ID) . '">'.$read_more_text.'</a>';
}
add_filter('the_excerpt', 'excerpt_read_more_link'); | No idea if this makes a difference, and don't know about the Genesis either but give it a shot
function excerpt_read_more_link($output) {
global $post;
if ( 'speaker' == get_post_type() ) { $output .= '<p><a class="speaker-more-link" href="'. get_permalink() . '">View Speaker Profile</a></p>'; }
elseif ( 'resources' == get_post_type() ) { $output .= '<p><a class="speaker-more-link" href="'. get_permalink() . '">More Resource Content</a></p>'; }
else { $output . '<a class="more-link" href="'. get_permalink() . '">Read more</a>'; }
return $output;
} add_filter('the_excerpt', 'excerpt_read_more_link');
edit: and for the record, I don't know, for me the if/else logic seems solid. Not sure though, haven't really used any custom post types and it's really late and I'm half asleep :)
edit2: updated code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, genesis theme framework, read more"
} |
Show part of front page on another page
I'm using the Zerif Pro theme on my wordpress website: <
I've added content to the frontpage by customising the theme. I'm trying to show a part of the frontpage on another page.
I have "Packages" on the frontpage, and I'm trying to show this on my "Prices" page as well. I've tried different things, but I can only get it to show nothing or more or less the whole front page. How can I include only this part? | You must separate the template file who you want Like
get_template_part('file_without_php'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, content"
} |
Function returns post URLs rather than retrieving Facebook Graph API data
require('../wp-blog-header.php');
query_posts('&showposts=-1&order=ASC');
while (have_posts()) : the_post();
$url = the_permalink();
$json = file_get_contents( ' . $url . '%27' );
$json_data = json_decode($json, false);
echo $json_data->data[0]->total_count;
echo '<br>';
endwhile;
The above code, rather than returning the total share count, it returns the posts URLs.
How can I make it return the total_count value for each post ? I suspect line 6 needs to return URLs first before next line does the task..
Regards,
Thanks! | `the_permalink()` function doesn't return the post permalik, it prints the permalink. To assing the permalink value to `$url` variable you need to user `get_the_permalink()` instead:
$url = get_the_permalink(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, facebook"
} |
if user is admin display admin link and logout link else display logout only
Like the title suggest I would like to create a conditional with the ability to if user is admin display admin link and logout link else display logout only in wordpress. I have created this conditional but for some reason it is not working. I appreciate the help.
<?php
$admin_link= ("<?php echo bloginfo("siteurl") ?>/wp-admin/");
$logout_link= ("<?php wp_loginout(); ?>");
if (current_user_can("manage_options")) {
echo ' · <a href="' .$admin_link. '">Admin</a> ·';
echo ' · <a href="' .$logout_link. '">Admin</a> ·';
}else{
echo ' · <a href="' .$logout_link. '">Admin</a> ·';
}
?> | You've got some serious syntax errors - once you open that `<?php` tag, you're running PHP - no need to execute it again (i.e. inside your variable assignment strings):
if ( is_user_logged_in() ) { // Only show the output below if a user is logged in
$admin_link = esc_url( admin_url() ); // Escaped admin link
$logout_link = esc_url( wp_logout_url() ); // Escaped logout link
if ( current_user_can( 'manage_options' ) ) { // Current user is an admin, show the admin link
echo ' · <a href="' . $admin_link . '">Admin</a> ·';
}
echo ' · <a href="' . $logout_link . '">Log out</a> ·';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, conditional tags"
} |
Where to place add_action when enqueueing?
Do I place `add_action` before or after `function myTheme_script {enqueue functions here}` when enqueueing a script or stylesheet into functions.php, or does it matter? I'm seeing both from moderators on WP forums.
So...
function profondo_scripts() {
wp_enqueue_style( 'twentyfifteen-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'profondo-child-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'profondo_scripts' );
or...
add_action( 'wp_enqueue_scripts', 'profondo_scripts' );
function profondo_scripts() {
wp_enqueue_style( 'twentyfifteen-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'profondo-child-style', get_stylesheet_uri() );
} | Makes no difference. Despite the fact `add_action` doesn't actually check if the callback is indeed callable (i.e. is a valid function/class/method), PHP will first "load" function and class definitions before executing inline code, hence why you can do something like:
wpse_185390_function(); // Perfectly fine, even though the function is defined "afterwards"
function wpse_185390_function() {
echo 'I\'m down here!';
}
It's entirely up to you if you "hook" before or after the definition - I personally prefer after for consistency (it's how pretty much all WordPress core does it). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "actions, wp enqueue script"
} |
Subscriber role - blank page
I did a fresh install of WP4.2 today, but after playing for a while with setting up a custom user roles I realized that the built-in subscriber role is returning blank page instead of the dashboard.
Do you have the same problem? | I found an answer. It is because the WooCommerce plugin which prevents users without edit_posts capability to display dashboard.
Well, I think they should let you know that they are making this kind of change in WordPress default settings. Because you are not able to turn it off in WooCommerce settings. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, user roles, capabilities"
} |
Insert a variable in pre_get_posts
I've searched in google with no luck. I'm trying to add a variable into this code to modifiy the category of the posts in homepage:
Code Not Working:
<?php $p = $_GET ['p'] ;?>
<?php $catvar = get_cat_ID($p); ?>
<?php function my_home_category($query) {$query->set('cat', $catvar);}add_action('pre_get_posts', 'my_home_category' );?>
Code Working:
<?php $p = $_GET ['p'] ;?>
<?php $catvar = get_cat_ID($p); ?>
<?php function my_home_category($query) {$query->set('cat', 25);}add_action( 'pre_get_posts', 'my_home_category' );?>
When I manually put the id of the category the code is working and I only see the posts of that category. Any idea? Thank you! | You can not use a variable inside a function which has been defined outside the function! Get the value from `$_GET` inside the function.
function my_home_category($query) {
if (isset($_GET ['p'])) {
$catvar = get_cat_ID($_GET ['p']);
$query->set('cat', $catvar);
}
}
add_action( 'pre_get_posts', 'my_home_category' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pre get posts"
} |
Best way to create member pages for a lab website?
I lab I work for - implab.hu - would like to move migrate to a wordpress type site, but I have yet to find a similar plugin or template that imitates the function visible at < where you can see a link for each lab members profile, and afterwards as you click on it you are redirected to a Members style template page for their CVs.
I was wondering whether there is any elegant way to achieve this in Wordpress? | The plugin you're looking for is **Buddypress**!
With Buddypress you can have member profiles, activity streams, user groups, messaging, and more. With this plugin you can create a specific field or textarea called CV that will be outputed on the user's profile pages, this way your users can fill their CV by themselves.
If you're looking to just create pages instead of a social networking website, you can just create pages within Wordpress instead, and build this type of styling with CSS, here's an explanation on **how to create pages on Wordpress** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, pages, members"
} |
How to make is so the site logo can be changed easily without using the customizer?
I am working on my first wordpress site for quite a while. I'm building a site for someone who doesn't want to use the customizer, so this has been removed. You use to be able to click on apperance>header and not get directed to the customizer? You could change the site logo on a header page in the admin area.
Please can someone suggest a solution, for someone who doesn't want to use the customizer to change their site logo? It must involve no coding for the site admin.
Thanks! | Since going forward all themes in the theme repository will have to use the customizer for everything < I would expect any other functionality that have done similar things to be deprecated from core with time.
If you want different image upload functionality then best thing is probably to write your own and not to rely on the core to supply working GUI for it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "logo"
} |
Show author on every sub-page
Is it possible to display the author on all pages (not blog-entries) who created it? Every plugin I find is for blog-posts. | You need to add the following code to content-page.php in your theme folder.
<?php the_author(); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, pages, page template, author"
} |
Wrap a chosen category name with div
I'm trying to wrap a category name in a post with a div. This is how i get the category name I need.
Reference Links :
* `get_term_by`
* `term_exists`
My Ideas
<?php $term = term_exists('foo', 'category'); ?>
<?php $term = get_term_by('name', 'foo', 'category') ?>
I need to wrap `$term` in a div. But I still can't figure it how. | `get_term_by` returns an object by default, so you could output the term name using
<?php
$term = get_term_by('name', 'foo', 'category');
echo "<div>$term->name</div>";
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, taxonomy"
} |
How to change the displayed URL?
I'd like URLs like this:
`
be rewritten and displayed to a URL like the one below:
`
At the moment, the two URLs point to the same resource so there is no difference between them on the site apart from how they look like.
I'd like wordpress to display the shorter version.
How can I achieve this? | I think you shoud use some .htacess rexrite rules either than relying on the wordpress rewrite functions. It seems more appropriate in your case.
Try a rule like this :
RewriteRule ^root/([a-zA-Z]+)/([a-zA-Z]+)/$ /root/$2/ [R=301,L]
Insert it right after RewriteBase / | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
OAuth signature does not match
I am using the below in my wordpress for developing a oauth based application.
**WP-API** (api generating plugin)
**WP API OAuth1** (oauth server)and
**WP API client-cli** (oauth client library)
at the below url is for the wp client-cli <
I am getting this error **OAuth signature does not match** when I click the AUTH button for autherizing the request. I have tried all the fixed for this over the internet. but none helped
signature generated and sent from api client is **3ko8DUsUUEB4Hqaks68vGYnTjQM=**
signature generated in server side is **5rPsul6zplhfNvb4o+Mz11O/OyI=**
so the below code is failing
if ( ! hash_equals( $signature, $consumer_signature ) ) {
return new WP_Error( 'json_oauth1_signature_mismatch', __( 'OAuth signature does not match' ), array( 'status' => 401 ) );
}
I guess the API console is generating wrong signature. Please help me in solving this issue. | I was facing a similar issue when trying to use Client-CLI with OAuth 1.0a plugin, however I found a solution here on the official repository.
In the file `lib/class-wp-json-authentication-oauth1.php` on line `524`, change the following code:
$base_request_uri = rawurlencode( get_home_url( null, parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), 'http' ) );
to:
$home_url_path = parse_url(get_home_url (null,'','http'), PHP_URL_PATH );
$request_uri_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
if (substr($request_uri_path, 0, strlen($home_url_path)) == $home_url_path) {
$request_uri_path = substr($request_uri_path, strlen($home_url_path));
}
$base_request_uri = rawurlencode( get_home_url( null, $request_uri_path, 'http' ) );
This should solve the problem you are facing. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp api"
} |
How to customize sub-URLs in a wordpress website (.htaccess)
I have a regular business website that I built on Wordpress - www.example.com
I have a blog page in my website under - www.example.com/blog
When viewing a blog post it looks like this: www.exmaple.com/[category]/[posts-name]
How can I add "/blog" to this URL before the category? like this: www.exmaple.com/blog/[category]/[posts-name]
This is my current .htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress | You can not do that viw .htaccess because .htacces rules can not control how the permalinks are generated by WordPress. Instead, go to WordPress settings->permalink. Select custom structure and enter:
blog/%category%/%postname% | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, urls, htaccess"
} |
How to get sort content by page id?
I wont to get short content in my footer area. So, I write my code as follow:
$page = get_page_by_title( 'About us' );
$content = apply_filters('the_content', $page->post_content); ?>
<p> <?php echo $content; ?> </p>
By this code I get full page content. So how can I get short content till my setted `<--read more-->` link in the about us page? | I believe your best solution will be to setup postdata and the making use of the `the_content()` template tag
$post = get_page_by_title( 'About us' );
setup_postdata( $post ); ?>
<p> <?php the_content(); ?> </p>
<?php wp_reset_postdata(); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, content, export, read more"
} |
How to use 'WP_Query' or 'query_posts' to display content in a descending order
How can I list posts in a descending order of the `$json_data->data[0]->total_count` values ? I want to display top shared posts descending, but I can't really use `WP_Query` or `query_posts` the right way.
require('../wp-blog-header.php');
query_posts('&showposts=-1');
while (have_posts()) : the_post();
if ( has_post_thumbnail() ) {
the_post_thumbnail( array(40,40) );
}
$url = get_the_permalink();
$json = file_get_contents( ' . $url . '%27' );
$json_data = json_decode($json, false);
echo $json_data->data[0]->total_count;
endwhile;
The above code shows posts and total share count but not in a descending order because yet I haven't applied any rule.
Any thoughts ?
Thanks in advance!! | You can store the counts as key and link a value and sort them before display like this :
$sort_tab = array();
while (have_posts()) : the_post();
if ( has_post_thumbnail() ) {
the_post_thumbnail( array(40,40) );
}
$url = get_the_permalink();
$json = file_get_contents( ' . $url . '%27' );
$json_data = json_decode($json, false);
$sort_tab[$json_data->data[0]->total_count] = $url;
endwhile;
sort($sort_tab);
foreach($sort_tab as $count=>$link)
{
echo $link.' has '.$count.' votes';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, query posts"
} |
Create a shortcode to use in visual editor
I'm using Visual composer and i can't use php code inside boxes but i can use shortcodes. I know i must use function inside my functions.php file
I need only a example/help for one and i will contruct the rest of shortcodes.
<div class="header-image"><?php
$image = get_field('imagen_superior');
if( !empty($image) ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?></div> | Simple, make a shortcode:
function my_image() {
$image = get_field('imagen_superior');
if( !empty($image) ) {
echo '<img src="' . $image['url'] . '" alt="' . $image['alt'] . '" />';
}
}
function my_shortcode( $attr ) {
return '<div class="header-image">' . my_image() . '</div>';
}
add_shortcode( 'my-shortcode', 'my_shortcode' );
and then place `[my-shortcode]` in the visual composer. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortcode"
} |
Can we use a variable hook for language string?
I am using this to localize strings in my theme
__('Background image', 'themename');
there are plenty of strings that are localized but to make sure that the theme lang files and localization strings can be quickly changed, I would like to use something like this
$theme_name = 'themename';// this would be global var or var from a theme class
__('Background image', $theme_name); // or $myClass->themename
and than use that variable everywhere it is needed. This way the owner of the theme can quickly change theme name and does not have to walk trough all locaizations.
Do you see a problem with this ? | Yes this is problematic as i18n tools that parse your theme to generate a *.pot file for translation can't understand this as they do not run PHP code but just search your code as text.
Here is a blogpost detailing on why this may cause trouble:
> Bottom line: _Inside all translation functions, no PHP variables are allowed in the strings, for any reason, ever. Plain single-quoted strings only._
But nevertheless the fact that you think about DRY is great! Actually as I've already talked about the i18n tools they can help you with automatically adding a textdomain. There even is a Grunt plugin to automate this plus the option to replace/rename textdomains which would solve your actual issue. Just comment if you need more help on that. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "localization"
} |
New Menu Item Type Meta Box
I have a project I am working on where I need to pull in articles from a 3rd party API.
I've got this working using rewrites, but the last step I'm having trouble with is integration into the navigation.
What I'd really like is a separate meta box in the left hand column where I could ask for an article id and category and from that information add a custom link to the nav.
Is such a thing possible? I haven't seen much in the way of custom meta boxes from menu items.
Thanks, | Yes, this should certainly be possible, although as you have noticed it's not too common.
If you take a look at respective admin template the left column is built like this:
<?php do_accordion_sections( 'nav-menus', 'side', null ); ?>
Essentially they _are_ just metaboxes, though differently presented.
The defaults are handled by `wp_nav_menu_setup()`, which should be a good starting point to taking it apart.
Unfortunately I am not confident to weight in on JavaScript side of it, since that's not my area. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
Embed a Google Sheet as you view it in a separate tab?
Is it possible to embed a Google Sheet as you view it in a separate tab like in this website?
!image description
I have tried to use Publish to the web or the plugin Inline Google Spreadsheet Viewer but it just embed a simple sheet. My file has various sheets and lots of data so it will be great if visitors can make some complex action such as filtering or sorting. | Create an iframe in your post content, and set its source as the google spreadsheet! You'll probably want to create a shortcode for iframes as they're stripped out of post content automatically, but there are questions asking how to do that on this site | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, database, google docs"
} |
Display Upload Author & Get Uploaded Post ID
Working on a project with a lot of galleries & "attachment" post type queries. It's all working great except I noticed in the Attachment Details box in the admin dashboard that Wordpress stores & displays the attachment upload author & uploaded to post. So the question - does anybody have experience or know how to return the upload author & uploaded to post ID within the loop of a custom attachment query?
I've searched through the codex and stackexchange but haven't been able to come up with anything.
Thanks! | Attachments count as a built-in post type which is extremely similar to Posts and Pages. The field you're looking for is `post_author`.
If you have an attachment object:
$attachment->post_author
If you only have the attachment ID you can use
get_post_field( $attachment_id, 'post_author );
To get the actual Post the the attachment was originally uploaded to you can use:
$post->post_parent | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query"
} |
How to find the Registration page
I am managing the WordPress website i don't have the document of the website my problem is the website has the registration page please see [this link]
but when i check the registration page in WordPress admin the page is blank i don't have any idea how the previous developer linked the page can anyone help where to find the page. | This is a `buddypress` page, linked with the page ID 4275. The body class of your delivered HTML is:
<body class="registration register buddypress page page-id-4275 page-template-default admin-bar no-customize-support no-js">
To edit this page itself, go to
BuddyPress filters the content of this page and adds a registration form.
To modify the registration form itself, please refer to the BuddyPress documentation.
_BTW: Seems like you have got a lot of work to do, cleaning all this up. Just at glancing at it I found 36 stylesheets and 61 Javascript files, as well as inline scripts, from at least 22 plugins plus your theme and child theme.._ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, user registration"
} |
How to create cutom link for page
I am newbie in WordPress, and my question may be duplicated, but I cant get this, help please. I have page with this URL: `example.com/?page_id=49`, but I want to make it as `example.com/test_page`. Thanks! | Change `Settings -> Permalinks` to Post Name.
Go to your page and edit the Permalink field below the title field. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, url rewriting, urls"
} |
How to stop wordpress from changing default .htaccess permissions to 444
I installed my website using an installer - fantastico for a quick install.
Just a few days ago, I started getting a weird error in w3tc plugin and it would ask me to update via ftp as you can see below:
!w3tc error message
I found out the file permissions for htaccess have been changed to 444
No matter how many time I try changing it manually, it becomes 444 after a while (about 30 seconds or if I do something in wp dashboard)
!permissions set to 444 :\(
For a while, I am able to rewrite the rules and then the file gets reverted to what you see below:
!htaccess reverts to this
I have Hostgator's shared hosting.
Is there a way to combat this issue?
Edit: I have tried adding ftp details to my wp config too. Didn't help | Your site has likely been hacked. My site had the Darkleech infection, which injected some malicious code into `wp-includes/nav-menu.php`, causing .htaccess to reset to 444 on any page load.
I'd recommend you install the Sucuri plugin and let it restore any files that have been corrupted. Assuming your site was hacked, use their Post-Hack tab to reset plugins, passwords, and keys. Also check to make sure another admin user wasn't created. Use their Hardening tab to secure as much as you can. You could also install Wordfence for more security.
If you make adjustments and the problem keeps coming back, you likely have a root-level breach on your server, and then you have to work with your hosting provider to try to clean out the infection. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 5,
"tags": "plugins, htaccess, permissions, plugin w3 total cache, ftp"
} |
How to change the descriptive text on the menus admin page?
On the menus admin page, it says 'Drag each item into the order you prefer. Click the arrow on the right of the item to reveal additional configuration options.'
I would like to modify this to ' Drag each item into the order you prefer. The maximum top level pages is 6'.
How can I do this? Thanks. I have been trying to figure it out but have got no where. | The text you are referring to is located in here: `wp-admin/nav-menus.php`. But we will not edit directly. We will use `functions.php` for the convenience of preserving the changes after an upgrade.
Use the following code in `functions.php`
add_filter( 'gettext', 'wps_translate_words_array' );
add_filter( 'ngettext', 'wps_translate_words_array' );
function wps_translate_words_array( $translated ) {
$words = array(
// 'word to translate' = > 'translation'
'Click the arrow on the right of the item to reveal additional configuration options.' => 'The maximum top level pages is 6',
);
$translated = str_ireplace( array_keys($words), $words, $translated );
return $translated;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin, wp admin"
} |
How to building pretty URLs to reflect category hierarchy?
At the moment, this is how I access brands (custom post type) on my page:
`
I would like to access brands like this:
`
This is reasonable, bacause each `<brand>` lives in a `<sub_category>` so I'd like to have it reflected in the URLs (and later, breadcrumbs).
The permalink on the admin edit page for brands is also `
How can I build URLs that I'm after - so that `<brand>` is prepended with `<category>` and `<sub_category>` ? What are my options ? | Change the **`Settings -> Permalink`** to Custom Structure **`/%category%/%postname%/`**
Now while editing the post, check only the **`subcategory`** and now the parent category is nested within the URL automatically. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "url rewriting, urls, rewrite rules"
} |
Clean up very big and very dirty database
I'm trying to clean up a database in order to move a website from a server to another. Database is more than 1gb, mostly posts revisions and spam comments.
Is it safe for instance to do something like this?
DELETE FROM wp_2_posts WHERE post_name LIKE '%revision%'
Thanks. | Yes, it is safe but always prefer a database backup before. You can also try the Minimise WordPress DB queries to clean more. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, customization"
} |
Are styles included in a stylesheet using add_editor_style loaded in the front end?
I am writing a stylesheet that will help show the content in the TinyMCE editor look more like it would appear on the front end of the website using the add_editor_style function in the WordPress theme functions file. I may even end up adding a few style rules in the editor-style.css file just to be used on content.
So I am wondering if the styles added to the editor-style.css stylesheet are also loaded on the front of the website when the page gets rendered? I checked the WordPress documentation and I didn't see anything that specifically stated one way or the other.
add_editor_style( "editor-style.css" );
**UPDATE**
Here is the actual code from the themes functions file:
function custom_theme_features() {
add_editor_style( 'css/editor-style.css' );
}
add_action( 'after_setup_theme', 'custom_theme_features' ); | Below is the full code to include the editor style in a common way.
<?php
function my_theme_add_editor_styles() {
add_editor_style( 'custom-editor-style.css' );
}
add_action( 'admin_init', 'my_theme_add_editor_styles' );
?>
When you are adding the custom editor style, you need to use `admin_init` hook which is triggered only when you are inside the admin panel. So the stylesheet will not load in the front end and is limited to admin dashboard. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "add editor style"
} |
Wordpress Plugin to Show a Website in Different Language?
Well I am looking for a plugin which will let visitors to browse a site in different languages. Lets say an user just landed on my site and a popup will be appear asking whether the visitor want to browse the site into English or Bengali? If the user select on Bengali then the site will be shown to him in Bengali language otherwise it would run into its default language.
Is this possible? If possible then please guide me to implement it in my site. | This plug-in works well, though you typically have to create separate subdomains for each language.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins"
} |
comment_post action hook running on page load instead of after a comment is posted
I am trying to call a function after a comment is saved to the database, see below...
add_action('comment_post', 'myFunction', 10, 2);
do_action('comment_post', $comment_ID, $comment_approved);
I have placed this code in my `comments.php` file. `myFunction` is defined in `functions.php` and is shown below
function myFunction($comment_ID, $comment_approved){
Analytics::track('Posted comment!');
}
The problem is that this function is getting called every time a page containing the comment form is loaded not just when a comment is posted...
Any thoughts on why this is happening???
I guess a work around could be to call the function on page load only when the page is being loaded from `wp-comments-post.php` but I don't know where to even start trying to achieve this...
Any help is appreciated! | Your action is called whenever `comments.php` loads because you're explicitly running it with `do_action`. Both the function and `add_action` should be in `functions.php`, and `do_action` should be removed entirely. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments, comment form, comments template"
} |
Force Log in to view a page
So I have a page (ex. site.com/start) where I want to show a login page (ex. site.com/start/login) if not logged in, in order to view the page.
Without using any plugin, what would be the condition logic which if user visits `/start` page, while they are not not logged in, then the user is redirected to `/start/login` page instead?
Thanks. | In a template file, this should do it:
<php
If (!is_user_logged_in())
{
wp_redirect( "start/login" );
exit();
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "conditional content"
} |
Notice: Use of undefined constant SCRIPT_DEBUG
I'm getting this error at the top of my wordpress site:
> Notice: Use of undefined constant SCRIPT_DEBUG - assumed 'SCRIPT_DEBUG' in /[wordpress path]/wp-includes/formatting.php on line 4144
No idea where it came from, any ideas what started causing this?
Using version 4.2.1 | This is a known bug
As far as I'm concerned, you can easily fix it by replacing
if ( SCRIPT_DEBUG ) {
with
if ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) {
That should suppress the error for now.
When Wordpress is updated again, this error may be overwritten, but I believe it will be fixed in the next update.
**UPDATE**
Fixed at build 32482. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "errors"
} |
Firebug and Chrome rendering two body tags
I have a curly problem I've been working on for some time. At first it appears as if the get_body_class() function was broken but after I removed it from the template the issue persists.
<html class="js firefox">
<head>
<body>
<body>
<div class="top_div">
<div id="page" class="hfeed site logo">
<div id="page" class="hfeed site">
<div class="footer_wrapper">
</body>
Yet when I view the same via page source I see only one body tag.
I am using the latest version of Wordpress and all plugins are up to date.
Things I have tried to resolve the issue:
* Disabling all plugins
* Changing to default theme
* Replacing the wp-admin folder
* Forcing UTF-8 without BOM encoding on all PHP files
Note that if I completely remove the body tag from the header.php file I only see a single body tag in Firebug and in page source I see the following:
!pagesource screenshot | I managed to fix this issue by commenting out the first body tag and placing a second body tag below like this:
<!--
<body>
-->
<body <?php body_class( $class ); ?>>
Now the site is working correctly. However the strange character is still appearing in the first body tag.
Hope this helps someone. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, filters"
} |
Output string using php printf
I'm trying to display a texts with functions on my page. Please find the code below. I'm not getting the output I want.
<?php $content = the_content(); ?>
<?php printf(__('Output : %1$s', 'theme'), $content); ?>
Which Outputs :
Foo
Output :
I need my output to be like this :
Output : Foo
* * *
Answer from Kim Christensen :
<?php $content = get_the_content(); ?>
<?php printf(__('Output : %1$s', 'theme'), $content); ?>
Works perfectly :
Output : Foo
* * *
Answer from Pieter Goosen :
<?php $content = apply_filters( 'the_content', get_the_content() ); ?>
<?php printf(__('Output : %1$s', 'theme'), $content); ?>
It pushes my content below :
Output :
Foo | `the_content()` prints it output to screen. What you want is to return that output and assign a variable to it.
You should note, although `get_the_content()` do exactly what you want, it only returns unfiltered content, and not filtered content like `the_content()`. You should manually add those filters, which is real easy.
You can do the following
$content = apply_filters( 'the_content', get_the_content() );
## EDIT
It seems the above approach pushes the content part to the next line when the filters are applied to `get_the_content()`.
A work around here would be to concatenate `Output :` to `get_the_content()` and then applying the content filters to that
<?php $content = apply_filters( 'the_content', 'Output :' . get_the_content() ); ?>
<?php printf(__( '%1$s', 'theme'), $content); ?>
would give you what you need | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "content"
} |
Deleting a category from WordPress admin does it remove it completely from the database?
When you delete a category in the admin of WordPress does it completely remove it from the database?
I had a few categories with the same naming conventions (different slugs) but now deleting any categories having the same names and creating a complete new category but I wanted to make sure the old categories is completely erased out of the database, does this happen automcatically? | Yes, the categories are stored in `wp_terms` table which contains the term_id, name and slug. Deleting the category in admin panel removes the three values along with it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, database"
} |
is it possible to get the hook name in add_action?
given this:
<?php add_action( $hook, $function_to_add, $priority, $accepted_args ); ?>
Is there a way to get `$hook` value inside the function `$function_to_add`? | The name of the current hook is always `current_filter()`. Despite its name, this function returns the name of actions too.
Usage example: Move the textarea in a comment form.
The current priority is: `key( $GLOBALS['wp_filter'][ $hook ] )`. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "hooks, actions"
} |
Show only the future event (Advanced Custom Fields)
I’m trying to make event ticker with Advanced Custom Fields and I want to show only events that are happening on the current day or in the future. But I don’t know how to hide past events. Could anyone help me, please?
This is my code. It works fine, but it doesn't hide past events.
<?php $event = new WP_Query(array(
'post_type' => 'gacr-event',
'posts_per_page' => 5,
'orderby' => 'meta_value_num',
'order' => 'DESC'
)); ?>
<?php $date = DateTime::createFromFormat('Ymd', get_field('date')); ?>
<?php while($event->have_posts()) : $event->the_post(); ?>
<li>
Posted on: <?php the_field('date'); ?><a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?> | You need a meta query. There's also documentation on ACF for querying dates.
<?php
$event = new WP_Query(
array(
'post_type' => 'gacr-event',
'posts_per_page' => 5,
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'date',
'type' => 'NUMERIC', // MySQL needs to treat date meta values as numbers
'value' => current_time( 'Ymd' ), // Today in ACF datetime format
'compare' => '>=', // Greater than or equal to value
),
),
)
); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "advanced custom fields, events"
} |
Safely editing core files
I want to edit wp-comments-post.php so that if for example someone tries to post a comment with no content they will get a popup box telling them they cannot post an empty comment instead of the page redirect that happens at the moment.
if ( '' == $comment_content ) {
wp_die( __( '<strong>ERROR</strong>: please type a comment.' ), 200 );
}
Can someone recommend a safe way to do this to avoid my changes being overwritten with future Wordpress upgrades... | There is no "safe" way to edit core files; if you do you will need to check and repeat the edition after every update. Not recommended at all.
Instead of editing core files, you could use any of the actions and filters available. For example, pre_comment_on_post (example code not tested):
add_action( 'pre_comment_on_post', function( $post_id ) {
if( $post_id ) {
$comment_content = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null;
if ( '' == $comment_content ) {
// Redirect to post if comment content is empty
wp_redirect( get_permalink( $post_id ) );
exit;
}
}
} ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "comments, core, core modifications"
} |
How do you detect if a specific word is at the end of a the_title()
I have event listings that look like this
PAPA ROACH AT THE PARAMOUNT IN HUNTINGTON ON APR 28, 2015
Im trying to remove everything after the last "ON"
$s = the_title();
echo substr($s, 0, strrpos($s, 'ON') - 1);
The code above works if '$s' is a regular string but if it is 'the_title()' it does not work. Is there a way to convert the_title() in to a static string? | Try using the `post` variable to access the `post_title`
global $post;
$s = $post->post_title;
echo substr($s, 0, strrpos($s, 'on') - 1); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, query string"
} |
No Appearance panel is shown
I am completely new in WordPress. I must change visual appearance of some pages, but in admin panel doesn't shown appearance panel. To be a more concrete, i want to change navigation menu, to add some links. My WordPress version is 3.9.5. Any help is appreciated.
!enter image description here
!enter image description here | You are accessing your hosting server panel. There is no way you will find `Appearance` tab there. Go to this URL: ` to access your WordPress Dashboard. You can view the `Appearance` section there. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "pages"
} |
get_comment_link without pagination base in the returned URL?
On pages with paginated comments get_comment_link returns URLs in the following format:
How could I make it return a URL like this?
| It's strange that you want to use comments pagination where the comment links are without the comments pagination base.
But you can try this (untested):
/**
* Remove the comments pagination base from comments links
*/
! is_admin() && add_filter( 'get_comment_link', function( $link, $comment, $args )
{
if( $args['per_page'] )
$link = sprintf( "%s#comment-%d",
get_permalink( $comment->comment_post_ID ),
$comment->comment_ID
);
return $link;
}, 10, 3 );
Another option would be to replace it with something like:
$link = preg_replace( '%comment-page-\d+/%', '', $link );
where the base could be dynamically fetched with:
global $wp_rewrite;
if ( $wp_rewrite->using_permalinks() )
$comments_pag_base = $wp_rewrite->comments_pagination_base; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
mp4 video preview
Our webpage is using WordPress 4.2.1 running Virtue - Premium theme.
When I insert a video using visual editor, e.g.
[video width="1280" height="720" mp4="
There is no preview on the webpage. It just shows a black video screen with an arrow.
Is it possible to display a still from the tenth second of the video instead? | You can manually add a thumbnail with the [`[video]`]( shortcode by making use of the `poster` attribute.
If you want to do it automatically, then you have to implement `FFMPEG` or `LIBAV` first, meaning they would have to be available on your server. Afterwards you could hook into `wp_generate_attachment_metadata` and automate process - I have given an answer how to do this for PDF's some time ago, just so you get an idea. But that of course will be quite some work.
I hear there are some pretty good plug-ins in the WordPress Plugin Directory, although I haven't used them myself. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "videos"
} |
Why are these settings unregistered?
After updating a WordPress site to version 4.2 (and the forced 4.2.1 security update), I get some weird deprecated errors:
> Functionality: Unregistered Setting
>
> The `post-type-menu-page` setting is unregistered. Unregistered settings are deprecated. See < Deprecated in version 2.7.
I have the same error for lots of other post types: `post-type-dashboard-page`, `post-type-menu-post`, `post-type-menu-forum` (this is from bbPress), `post-type-dashboard-post` and more.
These errors have been reported by the Log Deprecated Calls plugin. There is no line or file shown.
Why do I get these errors?
I don't care about the native WordPress post types, I just want to fix my own post types to be up to date with 4.2+.
**EDIT:** Based on the option's structure, I couldn't find any reference both to `post-type-` or `post-type-menu-` in WordPress' source code. | The error message is actually misleading here. WP isn't checking if the settings are registered -- e.g., `if ( isset( $GLOBALS['wp_registered_settings']['foo'] ) )` \-- it's checking if the form was posted to the default options page (`options.php`), rather than a custom one (`options-general.php?page=foo`).
So, it's entirely possible to get this warning after calling `register_setting()`, if you're doing something like this:
`<form method="post" action="options.php">`
You can just remove the entire `action` attribute, since it'll post to the current URL by default. In that case, it'll include the `?page=foo` parameter, so `$unregistered` won't be set. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "settings api"
} |
Custom function causes a 503 error after a couple of hours
I have a custom function written in PHP for a Wordspress theme. When I initially wrote it, it worked exactly as expected (it returns the parents and grandparents etc of a term from its ID).
However, after a couple of hours, it started throwing up 503 errors. Why would this only happen after a while? Is there some sort of memory leak that builds up over time?
$ancestors = $terms[0]->term_id.GetAncestors($terms[0]->term_id,$include);
function GetAncestors($term_id,&$include) {
$child_term = get_term( $term_id, 'category' );
$parent_term = get_term( $child_term->parent, 'category' );
$include.=','.$parent_term->term_id;
if($parent_term->parent!=11) {GetAncestors($parent_term->term_id,$include);}
return $include;
}
Is it the function itself that's causing the issue, or some way I'm using it, e.g. using a reference from an object as one of the variables? | What about using the WordPress function `get_ancestors()`, which
> Returns an array containing the parents of the given object.
To be exact an
> Array of ancestors from lowest to highest in the hierarchy
We can easily create a function to return a list by using `implode` to do so:
function wpse185971_get_ancestors_list(
$object_id,
$object_type = 'category',
$separator = ','
) {
$ancestors_array = get_ancestors( $object_id, $object_type );
$ancestors_list = implode( $separator, $ancestors_array );
return $ancestors_list;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions"
} |
How to get_template_directory() properly on local environment
I'm currently developing a site locally in MAMP PRO. When I use get_template_directory() inside of the standard functions.php file, the site path gets output correctly. However, I have a separate enqueue.php file that I use to enqueue my scripts.
I'm using a require to include the enqueue.php file.
require get_template_directory() . '/inc/enqueue.php';
My issue begins inside of enqueue.php. Whenever I try to use get_template_directory(), instead of returning the correct site path, I keep getting the following output:
I can't seem to figure out why the /Users path gets added to the URL when I'm not in the functions file.
Any help would be greatly appreciated. | `get_template_directory()` returns a filesystem path-- that is, it returns the path to the file as it would appear if you were browsing it on the local machine via a file browser.
> Return Values
>
> (string) Absolute path to the directory of the current theme (without the trailing slash).
>
> <
That is what you are seeing. The function works correctly (based on my interpretation of your question, anyway).
You want `get_template_directory_uri()` instead, which will give you a path relative to your web server root and which is what `get_bloginfo('template_directory');` gives you. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, localhost, site url"
} |
How to conditionally pass a parameter to wordpress search to limit post types?
I have a site with a subsection containing a custom post type, "artwork"
I have an overall site search working how I'd like it to - it searches all of my posts and custom post types. I would like to add a second search inside of my artwork subsection, that only searches the "artwork" custom post type. I know I can limit my search results like this:
function mySearchFilter($query) {
if ($query->is_search) {
$query->set('post_type','artwork');
};
return $query;
};
add_filter('pre_get_posts','mySearchFilter');
But that affects the sitewide search too. How can I set the post type ONLY on certain instances of the search form? I don't need a dropdown or any way for the user to choose, there are just certain pages where I'd like to include limited search instead of the overall site search. | If you have a "natural" artwork archive (typically setting `has_archive` to `true` in your `register_post_type()` arguments), you already have the functionality in place:
...assuming `artwork` is your archive slug, WordPress will search only artwork for "query".
Just set the `action` attribute of the search form to the archive URL, like so:
<form action="<?php echo get_post_type_archive_link( 'artwork' ) ?>"> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "search, pre get posts"
} |
Log of Heartbeat Calls
I've read that Heartbeat can slow a WP site down and I'm assuming if our admins/store managers have a lot of admin windows/tabs open, this will exacerbate the issue.
If yes, is there a condition to test and log the calls that Heartbeat makes so I can see if the site slowdown could be related to an excess of Heartbeat calls?
I had a look in the documentation and elsewhere but only found ways to deregister the script ( `wp_deregister_script('heartbeat');` ) - not what I need.
Or am I barking up the wrong tree and this is something that should be monitored via server logs, by watching: `/wp-admin/admin-ajax.php` ? | From quick look at the code, there is number of hooks firing in `wp_ajax_heartbeat()`. Out of which `heartbeat_tick` action seems quite appropriate to hook some logging logic too.
For the sake of completeness, while you are interested in logged in activity, the hook would be `heartbeat_nopriv_tick` for logged out users. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "logging, heartbeat api"
} |
How to load css in the footer
I was trying to move the load of my style.css in the footer of my wordpress theme. I have already done something similar with 2 js files and it works fine, they load in the footer:
function my_init() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery', ' false, '1.3.2', true);
wp_enqueue_script('jquery');
// load a JS file from my theme: js/theme.js
wp_enqueue_script('my_script', ' array('jquery'), '1.0', true);
}
}
add_action('init', 'my_init');
Now i was trying to move in the footer also the style.css, and keep only some inline css rules in the tag. I have tried wp_enqueue_style but it seems doesn't work well for me.
Someone could help me for find a smart solution? | Actually all styles should be placed in header. So WordPress doesn't have a parameter for doing this in the `wp_enqueue_style` function, because traditionally all styles were added in the `head`. Recently, many sites have moved to a system where critical "above the fold" styles are loaded in the head, while other styles are loaded in the footer.
So here is a way to to this: You can use `print_late_styles()` function which is called in footer. You just need to enqueue your styles when header is already passed.
So you need to find some hook which is called on each page and after `wp_head` hook. For example `get_footer` could be one.
function prefix_add_footer_styles() {
wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );
};
add_action( 'get_footer', 'prefix_add_footer_styles' ); | stackexchange-wordpress | {
"answer_score": 40,
"question_score": 22,
"tags": "wp enqueue script, wp enqueue style, footer"
} |
Disable Admin Bar Render on Plugin Page
In the WP Admin panel, I have a plugin that does certain calculations based on input from a form. I need it to print pretty, so I am attempting to render the plugin page without the admin menu etc.
I thought that `remove_action( 'wp_footer', 'wp_admin_bar_render', 10000 );` would accomplish this, but it seems to not be working as it still renders the admin panel, and not just a blank white page.
Here's what I have:
public function cpui_setup()
{
add_submenu_page( NULL, __( 'WooCommerce Print Order Recipe', 'woocommerce' ), __( 'Print Recipe', 'woocommerce' ) , 'manage_woocommerce', 'cpui_print_recipe', array( $this, 'print_recipe_page' ) );
}
public function print_recipe_page()
{
remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 );
require_once( 'admin/print_recipe.php' );
}
...
What am I overlooking? | In modern WordPress toolbar is considered _mandatory_ part of admin. That is WordPress is explicitly opinionated about not letting you to disable it. While you still can kind of hack it out, it's unnecessary struggle.
If you need a blank page there is no reason to struggle with blanking admin interface for it. You could simply use `wp-admin/admin-post.php` to handle your form. Ajax endpoint would work just as well, or maybe even custom "pretty" URL endpoint. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, woocommerce offtopic, admin bar"
} |
WordPress Page Column Problem
The sidebar which should be on the right side is being loaded below the content. How do I move the sidebar to the default position?
Here's the link | It's because of the extra class `row` wrapped.
After the `container` class
<div class="container">
Remove this code of class `row`
<div class="row">
and also remove the extra closing div if added for it.
The sidebar will be positioned to the right side. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "posts, pages"
} |
How do I add image to the title of post?
I installed rownling theme. How do I add image to the title of post? Please see the screenshot.
!enter image description here | Those are called `Featured Images` in WordPress.
While creating a new post, on the right hand side, you will see a meta box which allows you to upload an image. The image uploaded is cropped and set as the featured image.
More about it here: WordPress Featured Images | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins"
} |
Exclude posts from widget while post is showing on home, single and categories
Im using this widget.
but im trying to figure out how to get it to not display any posts that are currently being
displayed on the home page, single post and categories.
Another user raised the same question here
Which provided the following solution:
add_filter( 'rpwe_default_query_arguments', 'rpwe_exclude_current_post' );
function rpwe_exclude_current_post( $args ) {
if( is_singular() && !isset( $args['post__in'] ) )
$args['post__not_in'] = array( get_the_ID() );
return $args;
}
It worked but for single posts only not for posts in home page or categories. | Specific support for third party plugins are off topic, but your question can be answered in a general scope. `get_the_ID()` will not work for this specific issue, what you need is an array of post ID's that is currently being displayed on the page you are viewing.
The current array of posts that is being displayed on any given page is stored in the `$posts` property of the main query or any custom instance of `WP_Query`. It is from here that you would want to extract all the post ID's from to pass to `$args['post__not_in']` in your code in question.
You can try the following in your code above
global $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
Then you can feed `$post_ids` to `$args['post__not_in']`
$args['post__not_in'] = $post_ids;
You just need to pass the correct conditionals to target your specific pages | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, widgets"
} |
Taxonomy-$taxonomy-$term not working
This question might seem very simple, but I cannot find a proper answer for it. In my example I should have multiple pages that should display 'FAQ'. For that I have added custom taxonomy `page_type` to default `page` post type and set 'FAQ' as `page_type` for those pages. Now, according to documentation :
> taxonomy-{taxonomy}-{term}.php - If the taxonomy were sometax, and taxonomy's term were someterm WordPress would look for taxonomy-sometax-someterm.php. In the case of Post Formats, the taxonomy is 'post_format' and the terms are 'post_format-{format}. i.e. taxonomy-post_format-post-format-link.php
In my case, I add `taxonomy-page_type_faq.php` template file, but wordpress keeps using the default `page.php`.
What am I doing wrong ? | The `taxonomy-$taxonomy-$term.php` template is a template for an archive, a listing. It's not a template for a post, be it a post of type page, or anything else. It overrides `taxonomy-$taxonomy.php`, then `taxonomy.php`, then `archive.php` followed by `index.php` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, template hierarchy"
} |
Searching for meta_key returns 0 posts
I am currently on a client project and I am stuck with the `meta_key` search in `WP_Query`. I am querying some other parts of the homepage successfully with the `WP_Query` class, but when I am passing `array( 'meta_key' => 'views' )` into the `WP_Query` initializer it's not working and no posts are returned (I am using the WP-PostViews plugin for the views counter, if this is the problem.
Would be nice to have someone with a fix. **Thanks!** | To narrow down the possible causes I'd strongly recommend using a debugging plugin on your development server, like Query Monitor, so you can see the SQL being generated by your query. Alternatively check the `request` property of your `$wp_query` object.
It's always possible, if you only recently installed the plugin, that there aren't any posts with that post meta. Looking at WP-PostViews' source code and testing it myself I've found it only adds or updates the `view` post meta when a post/page is published or when it's visited. As such, any posts/pages created before the plugin was installed that haven't been viewed since will have no post meta. If you've been on the admin end of your dev server this entire time then it's possible there legitimately are no posts with any `views` post meta. If you check the `wp_postmeta` column of your WP install you can check this for yourself. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, meta query, views"
} |
Is it possible to make invisible a div only on certain pages using CSS?
I have a `div` with a unique `id`, and I need to make this `div` invisible but only on certain pages.
Using only CSS is it possible a solution like this?
#my_div{
display: inline-block;
}
#my_div .post5187{
display: none;
} | You need to target the specific pages with the build in `body_class` selectors.
> Themes have a template tag for the body tag which will help theme authors to style more effectively with CSS. The Template Tag is called `body_class`. This function gives the bodyelement different classes and can be added, typically, in the header.php's HTML body tag. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "css"
} |
How can I display my meta value in a textarea?
I have this saved:
$description = get_post_meta( $postID, 'video_desc', true );
and then have used this in my form in textarea:
value="<?php echo $description; ?>"
When I check the console it is there as the value but it is not displaying in the textarea. I am wanting this to show the text as it is in a edit-post.php page/file.
I have been searching for hours!! Any help would be much appreciated. | The value of the textarea must be printed between the opening and the closing tag:
<form action="/">
<textarea name="whatever"><?php echo esc_textarea( $description ); ?></textarea>
</form>
Note the usage of the function `esc_textarea()` here. It prevents any possible character inside the variable `$description` from being interpreted as HTML. It's an important step to avoid possibly XSS vulnerabilities.
There are many more escaping functions like `esc_attr()`, `esc_html()` or `esc_url()`. You should know about them and how they are meant to be used: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "post meta, text"
} |
Return on a quest all these meta_value
<?php
if(isset($_REQUEST['src'])):
$business = $_REQUEST['srcbusiness'];
$type = $_REQUEST['srctype'];
$price = $_REQUEST['srcprice'];
$city = $_REQUEST['srccity'];
$district = $_REQUEST['srcdistrict'];
$query = (array('post_type'=>'post','category_name'=>$business,'meta_value'=>$type,'meta_value'=>$price,'meta_value'=>$city,'meta_value'=>$district));
endif;
?> | You need to use a meta query:
if ( isset( $_REQUEST['src'] ) ) {
$query = array(
'post_type' => 'post',
'meta_query' => array(
),
);
if ( isset( $_REQUEST['srcbusiness'] ) ) {
$query['category_name'] = wp_unslash( $_REQUEST['srcbusiness'] );
}
$fields = array(
'srctype',
'srcprice',
'srccity',
'srcdistrict',
);
foreach ( $fields as $field ) {
if ( isset( $_REQUEST[ $field ] ) ) {
$meta_query[] = array(
'key' => $field,
'value' => wp_unslash( $_REQUEST[ $field ] ),
);
}
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query"
} |
Programatically change post author
Given a user id, $user_id, and post id, $post_id, how can I programatically update a wordpress post author?
Note: these posts are already created and the author cannot be set upon creation. Another process is creating the post and defaulting to the admin as the author. I don't have access to creating the post but have access after it is created. | It shouldn't be any problem. Try this:
$arg = array(
'ID' => $post_id,
'post_author' => $user_id,
);
wp_update_post( $arg ); | stackexchange-wordpress | {
"answer_score": 23,
"question_score": 10,
"tags": "author, wp update post"
} |
Insert Facebook button into header
I am trying to add a Facebook button to the center of my header image. I have tried adding a link to my header.php on different sections, but it either displays the button above or beneath the logo, instead of inside the image. Any suggestions on where I should insert it?
Website: <
Image: < | You need to add `position: absolute` to your Facebook button.
**Header.php**
<div class="logo">
<a class="logoimga" title="Gelnagels Gina" href="
<img src="
</a>
<a class="header-img-1" title="Facebook-header" href="#">
<img src="
</a>
</div>
**CSS**
.header-img-1 {
left: 15%;
position: absolute;
top: 50px;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "headers, facebook, header image"
} |
How to check if user meta field is empty in conditional else statement
Hello all I have a custom post type set up for my wordpress site within this custom post type i have a meta box with about 11 meta fields that I have added programatically. What I would like to do is check if one of the fields (which i have programmed to be a radio box)has a value if it does i would like to display the value of the field. If not then i would like to echo out the word Available. This is what I have been trying so far:
<?php
$consignment= get_post_meta($post->ID, 'availability', true);
if (empty ($consignment)) {
echo "avaliable";
} elseif ($consignment > 1) {
echo "$consignment";
}
?>
I would really appreciate the help. | Does this do the trick?
$consignment= get_post_meta($post->ID, 'availability', true);
if ($consignment == '') {
// code to run if the above is empty, eg.
echo "avaliable";
} else {
// else the code, eg.
echo $consignment;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom field, metabox, post meta"
} |
Wrapping add_query_arg with esc_url not working
I know about the XSS issue related to `add_query_arg()`function. That is why I am wrapping it with `esc_url()`.
Problem is...this is not working with `wp_remote_get()`.
If I go:
$url = add_query_arg( array( 'email' => '[email protected]',
'token' => '899A762614F6C49809A374FB955EC8C15'),
' );
$response = wp_remote_get( $url );
I am getting a valid body response.
But if I use esc_url on the `$url`:
$url = esc_url(add_query_arg( array( 'email' => '[email protected]',
'token' => '899A762614F6C49809A374FB955EC8C15'),
' ));
$response = wp_remote_get( $url );
The body response is "Unauthorized".
And the strange part: both codes echo the same string for $url!!!
Now what? | > And the strange part: both codes echo the same string for $url!!!
No, they don't. Look at the page source. `esc_url()` is encoding the `&` control character. You can't do that and expect the HTTP request to work correctly.
Use `esc_url_raw()` instead. Note the description in the Codex concerning that function:
> The esc_url_raw() function is similar to esc_url() (and actually uses it), but unlike esc_url() it does not replace entities for display. **The resulting URL is safe to use in** database queries, redirects and **HTTP requests**.
> < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "urls, escaping, wp remote get"
} |
Broken urls with http site and https wp-admin
I am currently using a wordpress installation in which all the website is intended to be shown in http while the https part is protected by a self signed certificate, distributed manually to the admins. The problem I have is that the images uploaded are all uploaded with the "https" prefix, I imagine because the link is generated somehow using the full path of the admin interface. Do you know how I can fix this behaviour to use the protocol http for every image uploaded? I don't really need https for this and the site name and URL is in http.
Thanks in advance.
Some specs:
* wordpress version: 4.2.1
* plugins installed: Category Posts Widget, Jetpack, Post Types Order, Relative Image URLs, WordPress SEO, WP Statistics. | I figured out the problem: the SEO plugin by Yoast is breaking the images as described, doing (probably) a URL rewrite at the time the media is upload. I resolved temporarily bye disabling the plugin. I will then find a better solution analyzing why the plugin is behaving in such a way and update my answer. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "images, urls, https, http"
} |
Custom term templates
So, I did some research online but could not find a solid answer, so here I am.
I am in need to make a custom woocommerce category page for a specific category.
For example, I have a category called "Awesome".
Instead of using a regular category page, generated by a shortcode`[product_category category="something"]`, I want to customized a specific category page for `Awesome`.
I found that I need to edit the `taxonomy-product_cat.php` file but I have no idea how to link it to the specific category called `awesome`.
In other words, I am thinking of making a custom copy of the php file then add it as a theme `template`.
Does anyone know how I can achieve it? | If you look at the template hierarchy, you need to create a template `taxonomy-{$taxonomy}-{$term}.php`. In your case, that template will be called `taxonomy-product_cat-awesome.php` where I assumed the **slug** of your term is `awesome`
Just a tip, the "categories" of a custom taxonomy is called `terms`. The build in taxonomy `category` "categories" is also called terms, but we call them in plain language categories. To understand this, you should check out this post | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "terms, template hierarchy"
} |
How to hide /wp-content/uploads/ from URL?
I have a Wordpress mulitsite and I want to hide the /wp-content/uploads/ part form URL in images and files.
The url now like this: <
I want to this: <
I try this in .htacces, but not working:
RewriteRule ^files$ /wp-content/uploads/sites/3/2015/05/VCC.jpg [L,QSA]
and this:
RewriteRule ^wp-content/uploads/(.+)$ [R=301,L] | Had you considered actually moving the folder?
WordPress allows to customize location of whole content folder or parts of it either.
According to moving uploads folder in Codex, as simple as:
define( 'UPLOADS', 'blog/wp-content/uploads' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugins"
} |
Changes in my child theme from customizer not appearing in style.css?
I have made some changes (colours, etc...) in the appearance customize from my child theme, is actually working as is just applying to my child, but when I open the style.css from my child I don't see any change, where these changes are? | If you mean the WordPress Customizer: These changes are not saved to the style.css, but they come most likely to be found shortly before `</head>`. Probably you will find there something like
<style>
//definitions via Customizer
</style> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "customization, child theme"
} |
wp-admin redirecting to https, denying login
I use cloudflare via the cloudflare plugin, have SSL enabled.
Enabled ssl within the wp-config.php file:
`define('WP_HOME','
`define('WP_SITEURL','
`$_SERVER['HTTPS'] = 'on';`
Everything seems to work fine on the main site, but when trying to login to admin I see:
You do not have sufficient permissions to access this page.
This started after going into general settings and adjusting the 'Home' and 'Site URL' options.
Following guides, I am able to get the page to appear (instead of being stuck in an infinite redirection loop).
I'm not sure what else to change here, as I've just lost permissions out right after switching to https everywhere. | You need to forward the http:// to https:// to avoid infinite loop.
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
$_SERVER['HTTPS']='on'; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "loop, permissions, https"
} |
Pages other than Home page not displayed even when URL is good
I installed WordPress on a dedicated server running Debian and each time a create a new page (www.mydomain.com/mynewpage) I can't access it, and when I try I get the error:
Not Found
The requested URL /mynewpage was not found on this server.
Even when I modify it in the WP admin board, If I click "Preview the changes", I get this error. The only page working is www.mydomain.com
Could anyone please help me ?
Thanks for your help
Matthias | After checking phpinfo(), mod_rewrite wasn't enabled so I enabled it:
<
and it worked ! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "urls, 404 error"
} |
Problem with Class, Filters and Callbacks
according to this Callback example if I'm referencing a method inside a class, I should use add_filter by specifying an array with 2 elements, first the object then the method. Here is my code:
add_action ('login_head', array('Admin', 'plugin_setup'));
class Admin
{
public function plugin_setup()
{
add_filter('login_headerurl', array($this, 'the_logo_url'));
}
private function the_logo_url()
{
return get_bloginfo('url');
}
unfortunately my code does not seem to work unless I move the function `the_logo_url()` outside the class. What's the best way of approaching this problem? | Here's a slightly modified version of your code snippet:
add_action( 'login_head', [ 'WPSE_Admin', 'plugin_setup' ] );
class WPSE_Admin
{
public static function plugin_setup()
{
add_filter( 'login_headerurl', [ 'WPSE_Admin', 'the_logo_url' ] );
}
public function the_logo_url()
{
return get_bloginfo('url');
}
}
The filter callbacks must be _public_ , not _private_. The reason for this is that `apply_filters()/apply_filters_ref_array()` are running `call_user_func_array()` on the stored filter callbacks, in the global `$wp_filter` array.
Also notice that you're not instantiating your `WPSE_Admin` class, so you can't use `$this`. You might want to use _namespace_ but I just prefix the class here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, callbacks"
} |
Add a description/hint field in the admin page of a plugin
I made a plugin and now I'm making an admin page for it. I know how to properly add a field in an admin page but do you know how I can add an description/hint field like this (grey text)?
Thanks | You can insert something like this:
<p class="description">This is my description</p>
The `description` class is a built in WP class that will produce the style of text you pointed out in your image. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, admin menu"
} |
How can I add a new page in the pages tab that belongs to specific theme?
Hi I would like to add new pages in my active theme but I dont want these pages appears when I move or active another theme.
I know these pages are saved in the database, but how can I link them to a specific theme?
thanks in advance for your help... | Pages are an independent entity separate from whatever theme is active at that moment.
This is the design paradigm of most CMS systems that separate the concerns of site content from the view or rendering layer which allows a site owner the chance to change how his site looks without having to worry about the contents.
HOWEVER, it would theoretically be possible to build a plugin or simply hook into the template activation system within wordpress to activate or de-activate certain pages on the fly... Or the plugin could conditionally render menu's based upon the active theme slug. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, themes"
} |
Separate the tag by comma
I am looking for a solution to separate the tag names by comma. The tag name i am using is without a link. Here goes the code:
<?php $my_tags = get_the_tags();?>
<?php echo $my_tags[0]->name?><?php $count=1;
foreach ($my_tags as $my_tag) {
if ($count != 1) {?>
<?php echo $my_tag->name?>
<?php }
$count++;
} ?>
The above code i got it from this page --> How to separate the tags?. But, the outcome is without a comma(,) if there are more than 1 tag.
Any solutions? Thanks! | This is actually more php related. Best will be to add your term names in an array and then use `implode` to convert it to a comma separated string
$my_tags = get_the_tags();
if ( $my_tags ) {
foreach ( $my_tags as $tag ) {
$tag_names[] = $tag->name;
}
echo implode( ', ', $tag_names );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tags"
} |
Block access to wp-admin
I'm attempting to use a .htaccess file to block access to the wp-admin folder. I've read through the Brute Force Attacks doc (< and I've added the block below, using my ip addresses, to the .htaccess file and placed it in the wp-admin folder:
# Block access to wp-admin.
ErrorDocument 401 default
order deny,allow
allow from x.x.x.x
allow from y.y.y.y
allow from z.z.z.z
deny from all
It seems to be working but the error that a user receives is "This webpage has a redirect loop". Is there a way to send the user to a 404 or another error doc instead of the redirect loop? I'm not really sure how that is occurring since there is nothing else in the .htaccess file.
I'm not password protecting the wp-admin folder and adding ErrorDocument 401 default doesn't seem to work either. | Placing the htaccess file in the wp-admin directory did not work for me so I went a different route and it seems to be working very well. Below is what I have in my **main** htaccess file:
<files wp-login.php>
# set up rule order
order deny,allow
# default deny
deny from all
allow from x.x.x.x
allow from y.y.y.y
allow from z.z.z.z
</files>
ErrorDocument 401 default
ErrorDocument 403 default
ErrorDocument 404 default | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "wp admin, htaccess, security"
} |
Safe to delete blank postmeta?
We have a lot of rogue custom fields. I feel that we can clear significant space in the DB if we remove the blank values. If I query my database with the following:
select * from wp_postmeta where meta_value = ''
I get 871038 (!)
My question is, is it safe to delete these? Are there any potential issues that could arise from doing this? | You should be fine deleting empty custom fields.
The main reason is, that `get_post_meta( $id, 'metakey', true )` returns an empty string if the field is not set, so it is the same as having an empty record set.
`get_post_meta( $id, 'metakey', false )`, returns an empty array if no value is set, so you should be fine too.
The only problem you could face is with getting all metadata at once (`get_post_meta( $id )`), because in the return to this call the empty values are set, but they are not set, if there is no record in the database. This could cause a few `PHP_WARNING`s, but you should be okay. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "post meta, mysql"
} |
Issues with add_query_arg() not passing a variable
I'm trying to pass a variable (`$homezip`) to the URL on a new page using `add_query_arg()`, but it's not working for variables although radius works fine.
$homezip = $_POST["search"];
$stringzip = esc_url( add_query_arg(
array(
'zip' => $homezip,
'radius' => '70'
),'' ));
<form action="/local-concert-listings/<?php echo $stringzip; ?>" method="post">
<input id="address" size="5" type="text" placeholder="Zipcode" name="search"/>
<input type="submit" value="go" name="SubmitButton" onclick="codeAddress()" />
</form>
I've been trying to turn `$homezip` into a string but nothing works. What am I doing wrong here? | I ended up using a GET method and got rid of add_query_arg() function
$homezip = $_GET["search"];
<form action="local-concert-listings/" method="get">
<input id="address" size="6" type="text" placeholder="Zipcode" name="zipcode"/>
<div style="display:none;">
<input id="volume" size="1" name="miles" value="70" placeholder="70"></input>
</div>
<input type="submit" value="go" name="SubmitButton" onclick="codeAddress()" />
</form> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
How to share plugin created database tables between two WordPress sites
I have two WordPress installs. One is a subdomain (Blog 2) and the other is the root domain (Blog 1). All tables are installed in same database. I am already sharing the users table, but am also trying to share a few plugin created database tables. Is this possible?
I used the following code in my wp-config to share the user tables:
define(CUSTOM_USER_TABLE,'wp_users');
define(CUSTOM_USER_META_TABLE,'wp_usermeta');
Is there a similar code to share plugin tables between sites? | I realized that all you have to do is find where the database is returned (in my case it is wp-init.php) and change the prefix to reflect the shared database:
$wpdb->prefix="wp_"; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "database, wp config, shared user tables"
} |
ACF Relationship - Limit to specific pages
In Advanced Custom Fields, I would like limit the Relationship field (< to specific pages.
For various resons, involing Custom Post Types is not a solution for me right now.
This is my sitemap:
website.com
website.com/contact/
website.com/help/
website.com/map/
website.com/hunting-products/
website.com/hunting-products/scopes/
website.com/hunting-products/rifles/
website.com/fishing-products/
website.com/fishing-products/fishing-rods/
website.com/fishing-products/bait/
In the Relationship field, and I would like to filter this so you only can select these products.
website.com/hunting-products/scopes/
website.com/hunting-products/rifles/
website.com/fishing-products/fishing-rods/
website.com/fishing-products/bait/ | Found a solution that works:
add_filter('acf/fields/relationship/query/name=products', 'exclude_id', 10, 3);
function exclude_id ( $args, $field, $post ) {
$args['post__not_in'] = array( $post, 9, 10, 11 );
return $args;
}
Added in functions. This will exclude the pages with id 9, 10 and 11. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "advanced custom fields"
} |
Redirecting to old domain after migration
I have moved one of my website to a new domain, below is what i did.
* Backed up database
* Uploaded all the files to the new server.
* Imported sql into new server via `phpmyadmin`
* Now i have used this script to change URL in database.
Now, problems i am facing are:
1. All the links are going to old domain.
2. All the images are linked to old domain.
3. `wp-admin` is also redirected to old domain when i try to run `mydomain.com/wp-admin`
Please help if you have any ideas about this, any help would be greatly appreciated. | My issue is resolved, I am posting this as an answer so that someone else can benefit out of it.
My issue was, `siteurl` and `homeurl` were not updated, so I have placed `define('RELOCATE',true);` in my `wp-config.php` file. And again tried to access the website , it gone to the correct URL but all the CSS was gone.
Then I headed over to `wp-admin` and it also came with no CSS but still I tried to login but this time it has taken me to the correct URL and with CSS login page but didn't log in. Then again I attempted to login and this time I was successful. Then I changed both the URLs from _settings_ in the admin panel.
After this you must to delete all your browser cache files to delete any kind of persistent redirection.
Hope this helps someone else dealing with the same problem. | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 20,
"tags": "urls, links, phpmyadmin"
} |
How can I execute some small piece of PHP code in a sandbox area of my WP?
I'd like to execute some small piece of code like the following one:
global $wpdb;
$rows = $wpdb->query('SELECT DATE(post_date) AS date, COUNT(*) AS count FROM ' . $wpdb->posts . ' GROUP BY DATE(post_date) ORDER BY DATE(post_date)');
foreach ($rows as $row) {
echo $row->date . ': ' . $row->count . '<br>';
}
But I don't want to write a plugin for this small task. How can I manage it? | Best way for execute any PHP code during development its Console from Developer plugin. You can install Developer plugin, and activate console module. "Debug" link will appear in top right corner in your admin bar. You can go there, and execute any php code you like. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, php"
} |
Unable to change Wordpress language (Wordpress 4.2.2)
So there's a website I'm working on and I need to change language to spanish. I downloaded and uploaded proper .mo and .po files and added the following value to my wp-config file:
define ('WPLANG', 'es_ES');
I've done this several times before and it's the first time it won't work. Maybe it's an issue with this Wordpress version? | You can set the language through your admin panel, go to 'Settings' > 'General', Scroll down and you will find an option for choosing the language.
This is a user friendly option to change the language. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp config, language"
} |
Make custom CSS changes and use built in theme customizer later?
Our company hired an outside developer to make changes to our WordPress header and theme colors. After he made the changes, we attempted to update the logo and change the header menu font color by using the built in appearance theme customizer, but this caused the changes to reset back to their previous form. (We have the Cherry framework.) We really don't want to have to hire a developer every time we'd like to make a small change.
The closest information I have been able to find is relating to creating child themes in order to keep customizations after updates.
Is it possible or what is the best way to make custom CSS changes and still be able to use the built in theme customizer? | I'm not familiar with the Cherry Framework but a quick search looks like the theme options allow for "Custom CSS" right under the General tab. To quote:
> Custom CSS - if you need to add some CSS rules, but you don't want to mess with the main CSS file, you can use this field. Just insert your new css rules.
<
Your other option is to use a child theme with a custom CSS file, like you mentioned. For just small CSS changes though, I don't see any reason why the Custom CSS option of the theme wouldn't work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.