INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Searchresult sidebar change
So, where is the searchresult page sidebar located?
For example, in the searchresult page, there is "A" sidebar.
However, I want to change it to "B" sidebar.
I looked at `search.php` but could not understand where the sidebar was coming from. | Your search.php may contain the following code
<?php get_sidebar(); ?>
If a name ($name) is specified as an argument then a specialized sidebar sidebar-{name}.php will be included. If sidebar-{name}.php does not exist, then it will fallback to loading sidebar.php.
If the theme contains no sidebar.php file then the sidebar from the default theme will be included | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sidebar"
} |
Return the most recently created custom taxonomy
I'm using a plugin (IssueM) which gives the "articles" post-type a custom taxonomy called "Issues".
I need to find and store in a variable the most recently created one of this taxonomy. So, for example, within `Issues` I have `issue-one` through to `issue-five` \- I need to return `issue-five` as it was created most recently.
How can I access this custom taxonomy by date? | Use get_terms to select that custom taxonomy, ordering by id DESC and returning only one record:
$latest_term = get_terms( 'issuem_issues', array( 'orderby' => 'id', 'order' => 'DESC', 'number' => 1, 'hide_empty' => false );
This presumes that your WP DB is set up normally, so the highest ID number on the custom taxonomy terms will be the most recently added term.
Also, make sure the _slug_ for the custom taxonomy is Issues, not issues. The slug query is case-sensitive. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy"
} |
Updating From Mobile App - Exposing Site to Hacking
I have made a simple Mobile App to update a wordpress site.
It starts with a login (to the app) and then with forms, sends data via POST method to a PHP file that then uses `wp_insert_post`, `wp_insert_attachment`, `add_post_meta`, etc to create the new post.
My concern is that this PHP page is not secure. If anybody got hold of the filename, they could insert anything to my site. My PHP file uses `include ("wp-load.php");` and then does its work, but I feel there is something I am missing as far as user verification that I can't figure out how to do via searching online. Any pointers to where I can learn about this would be appreciated.
I have tried to deconstruct the Wordpress Mobile App, but it is a little too complex for me. | The safest way to manage content from outside of the WordPress dashboard, and make use of the WordPress roles and capabilities model, is via XML-RPC.
The basic methods built in to WordPress XML-RPC allow you to add, edit and delete posts and media, and restrict the ability to do so based on WordPress user permissions. The problem is that it's a little complicated to use if you're new to programming, and the built-in XML-RPC methods are limited in terms of functionality.
For example, creating a new post with four images, and making one of those images the featured image, and adding different taxonomy terms to the post (categories, tags, etc.) based on some arbitrary criteria can require either making several XML-RPC calls in a certain order, or the need to create a custom XML-RPC method.
Here's a fairly basic primer on WordPress XML-RPC using the Incutio XML-RPC library, which is what WordPress core uses to handle XML-RPC requests: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, security, mobile"
} |
Website visible only to Registered users (non wp-admin)
I have created a page with a custom login using `wp_login_form()` function but how can I redirect all visitors to that page in similar way described in that topic?
My code looks like:
function redirect_to_login_if_guest() {
global $post;
if ( ! is_admin() && ! is_user_logged_in() && $post->ID !== 4667 ) {
wp_redirect( get_permalink(4667) );
exit;
}
}
add_action( 'wp_loaded', 'redirect_to_login_if_guest' );
but somehow is going into infinite loop instead of a login page. It looks like `wp_loaded` can't be used in my case.
Similar code moved to the `header.php'
global $post;
if ( ! is_admin() && ! is_user_logged_in() && $post->ID != 4667 ) {
wp_redirect( get_permalink(4667) );
exit;
}
works flawless so still it points on triggering action on `wp_loaded`. Any thoughts? | In short, the `$post` global isn't setup at the `wp_loaded` state. See:
* When and Where is `global $post` Set and Available?
for detailed information.
So use another hook, like `template_redirect`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "user registration, wp login form, content restriction"
} |
Multisite 404 errors and non-www redirecting to home page
My primary website on a multisite network was created with the `www` prefix (like `www.example.com`).
If I try to access pages without the `www` prefix (like `example.com/page-name/` instead of `www.example.com/page-name/`, I am redirected to the homepage (`www.example.com`). I would like to change this so I am redirected simply redirected to the same page URL, only with the `www` prefix.
Additionally, the 404 error page doesn't work on the primary site. No matter which non-existant URL I try (such as `www.example.com/thisdoesnotexist`), I am always redirected to the primary site home page (`www.example.com`), rather then seeing the theme's 404 page.
Here is a link to my site where you can test the issue. | There is currently a bug in the functionality that handles the `NOBLOGREDIRECT` constant, which causes 404 errors on the main site to be redirected to the value of the constant. Apparently this is the expected behaviour for sub-directory networks (`example.com/subsite`), but should not take place on subdomain networks (`subsite.example.com`).
There is a WordPress Trac ticket (#21573) concerning this bug, but there is no indication on when it might be resolved. Until then, you can resolve this error yourself by removing the `maybe_redirect_404` function:
remove_action( 'template_redirect', 'maybe_redirect_404' );
This code should go in a `.php` file in the `wp-content/mu-plugins` directory. Remember to include a `<?php` tag at the beginning of the file. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "multisite, redirect, 404 error"
} |
WordPress Installed But Not Showing Up!
I successfully installed WordPress on my domain. I FTP'd and installed it manually. But, something very strange is happening. Whenever I visit my website, the default WordPress Sample Post page is not showing up. Instead the Web Host's default page is showing up.
`www.example.com` and ` has same issue as mentioned above.
Please note that, I can successfully login to the ADMIN Dashboard. I have checked the permissions and have redone the permalinks. | Clear your browser cache or use another browser to load the site, this may be a cache issue. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, wp admin, permissions, ftp"
} |
How to filter posts in admin by before date or by post status 'future'?
I have read/searched a ton of questions but all I find seem to be related to custom post types and such.
The situation is that sometimes we happen to have a lot of posts waiting for to be published and I would like to preferably only show posts to a week from now (so all posts before `strtotime("+1 week"))` but if that's not plausable, I would like to filter out all posts by status "future" from the edit.php "all" view.
Can someone help me out?
function hide_future_scheduled($wp_query) {
global $pagenow;
if ($pagenow == 'edit.php') {
$wp_query->set(WHAT CAN I PUT IN HERE TO DO THIS);
}
}
add_filter('parse_query', 'hide_future_scheduled');
Thanks in advance. | The question pretty much got covered in another thread here.
In case anyone else need anything like this I ended up using following code to hide all the posts that are over a week in the future.
function hide_future_posts($where, $q) {
if(is_admin() && $q->is_main_query() && !filter_input(INPUT_GET, 'post_status') && ( $screen = get_current_screen() ) instanceof \WP_Screen && 'edit-post' === $screen->id) {
global $wpdb;
$where .= sprintf(" AND {$wpdb->posts}.post_date <= ( '%s' )", date('Y-m-d', strtotime('+1 week')));
}
return $where;
}
add_action( 'posts_where', 'hide_future_posts', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, admin, date, post status"
} |
Content alignment in Twenty Fourteen Theme
I am fighting around with a quite simple but at the moment not solvable problem.
I set up a WP site on an external server for trying first time WordPress and was successful. Now setting it up on an own internal server I got everything working, just one thing changed:
The content, never mind if page or blog entry is quite far away from the left side bar in twenty fourteen theme. Not so in the "Trial" installation, any idea?
CSS checked up and down and not found.
Twenty Fourteen theme. Navigation on the left and the top. Distance between right border of the left navigation bar to the text starting in the middle is so big. Text seems centered in the middle area.
So the main content area would be good to have more left aligned.
Thanks! | I recommend a tool like firebug (< It will give you the precise values and locations of the applicable css-styles in your style.css. If you use the same file in both installations there should be no differences except for different content or different devices. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, content, theme twenty fourteen"
} |
How to intercept update_option() before it saves data?
I am working with redux framework and need to save theme option values to a file right before it is saved in DB. Is there a way to intercept
update_option()
right before it saves data in DB? | You might be better off using the `update_option_` action instead. This will allow you to write to your file after the option has been updated (as apposed to before). If another plugin hooks into pre_update_option_ and alters the value after your plugin has saved it then you will have saved an incorrect value.
I would use:
add_action( 'update_option_myoption', function( $old_value, $new_value ) {
//Do something with the new value
}, 10, 2); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database"
} |
Removing posts and comments from Wordpress
I am using a plugin which creates both a custom post type for all my "posts" data and also another plugin which entirely handles the commenting system. Therefore I would like to entirely hide the comments and posts section from the site.
I currently have the following function:
function remove_admin_menus() {
remove_menu_page( 'edit-comments.php' );
remove_menu_page( 'edit.php' );
}
However this doesn't seem to do anything. Do I need to call this function anywhere to make it actually remove the menu items? | You need to "hook" it to an action, in this case `admin_menu`:
add_action( 'admin_menu', 'remove_admin_menus' );
Just place it right after the function. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "admin menu"
} |
how to use hook deleted_user into custom function to delete user from custom table
I have a second user table in my WordPress database for a separate application that I am integrating. I need to be able to delete a user from this second table when the user is deleted in the WordPress admin. I understand that the the add_action hook I need to use is deleted_user, but what would I use as an identifier in the WHERE clause of $wpdb->delete query? | Using the `delete_user` action you can pass in the `user_id` and use that as a basis to delete the user from your addtiional table. This is, of course, assuming you _use_ the `user_id` to make a relation between the two table. If not you can use `get_userdata()` passing in the `user_id` to get more user information. It would look something like this:
function custom_remove_user( $user_id ) {
// $user_meta = get_userdata( $user_id ); // IF you need additional user info before removal
...
}
add_action( 'delete_user', 'custom_remove_user', 10 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, customization"
} |
Using wp_send_json to return HTML
I don't understand how to return HTML correctly via AJAX.
I have this routine
function DisplayEventInfoBox()
{ ?>
<div id="eventInfo">
<div class="avail-from cart-right">
<?php
and so on...
}
If I include this in an AJAX call and the end of the routine is a die() the response object contains the HTML, which I can use as I like.
function myAJAXFn() {
DisplayEventInfoBox($my_page, $shipHelper);
die();
}
I want to send additional information, for instance using wp_send_json_success or another variable.
This code returns the HTML with the JSON array tacked on to the end. I would like a create a JSON object where I can access my page property and the html. What's the best way to do this?
function myAJAXFn() {
DisplayEventInfoBox($my_page, $shipHelper);
wp_send_json_success( array('page'=>$myPage) );
} | I can't tell what the $my_page, $my_page, or $shipHelper variables are supposed to do, but you can use an output buffer to capture the output of your DisplayEventInfoBox function. You can try the following:
function myAJAXFn() {
ob_start();
DisplayEventInfoBox($my_page, $shipHelper);
$my_html = ob_get_contents();
ob_end_clean();
wp_send_json_success( array('page'=>$my_html) );
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "php, ajax"
} |
Getting attachments by meta value
I'm stuck at a very simple point: I need to get all attachments by a custom meta key (and value). I'm developing a short code, so it has to work on every possible page.
What I've tried so far:
$args = array(
'post_type' => 'attachment',
'meta_query' => array(
array(
'key' => 'medientyp',
'value' => 'Video'
)
)
);
$query = new WP_Query($args);
But that does not find anything (yes, there do entries exist.)
Did I get something wrong? Or do I miss something? | I've spent hours of research and found the solution a few minutes after writing this question:
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit', <<-- IMPORTANT
'meta_query' => array(
array(
'key' => 'medientyp',
'value' => 'Video'
)
)
);
$query = new WP_Query($args); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 4,
"tags": "wp query, custom field, post meta, attachments, meta query"
} |
Conditional custom redirect
I want to achieve the following:
* On a post or a page, I can define an optional custom redirect URL (possibly as an Advanced Custom Field)
* If I view this post/page with a specific added URL parameter (like "?redirect=true", send a redirect to the defined custom URL, otherwise do not redirect.
My naive approach would be to add this as a javascript to the post/page template.
Is there a better option? Or a plugin I could (ab)use for that purpose? | It should not be tough. As you suggested you can use ACF to add a custom field in post/page and then use the template_redirect action hook to check if the current page's custom field is a valid URL as well as $_GET['redirect'] is true, wp_redirect to that URL.
function my_page_template_redirect()
{
if( is_url(GET_ACF_FIELD_VALUE( 'CUSTOM_FIELD' )) && !empty($_GET['redirect']) && $_GET['redirect'] == 'true)
{
wp_redirect( GET_ACF_FIELD_VALUE( 'CUSTOM_FIELD' ) );
exit();
}
}
add_action( 'template_redirect', 'my_page_template_redirect' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, javascript, redirect, advanced custom fields"
} |
How to Generate a list of Most Commented post?
I'm trying to call a list of most commented post. But the call to the DB returns always the same post (the first one in the loop)
This is my code in functions.php
function lugaresincreibles_most_commented() {
global $wpdb;
$pop = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE post_type='post' AND post_status='publish' ORDER BY comment_count DESC LIMIT 3");
foreach($pop as $post) :
get_template_part( 'content', 'featured' );
endforeach;
} | Primary issue with your function is "get_template_part" internally use global $post variable to display the post fields. However, your $post variable is filled for this function only. I would suggest to read this handy article Displaying Posts Using a Custom Select Query
Now, specifically in your case
function lugaresincreibles_most_commented() {
global $wpdb, $post; // make $post a global variable
$pop = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE post_type='post' AND post_status='publish' ORDER BY comment_count DESC LIMIT 3");
foreach($pop as $post) :
setup_postdata( $post ); // set the post data.
get_template_part( 'content', 'featured' );
endforeach;
wp_reset_postdata();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, loop, database, wpdb"
} |
Get link from wpe_excerpt "read more" and move it
I apologize in advance, I'm no wordpress developer, and am having a difficult time transitioning to cms dev from organic dev, so sorry if this is a simple question or has been asked in different words before.
Here's my question, I'm editing a page that echoes out excerpts via `wpe_excerpt` including the `read more` link. What I'd like to do is take that link and make the entire container for the excerpt and make it link to the content in question.
Of course I know how to make the container link to the content, but how do I get that link?
Thanks! | You might be interested in fetching the post's link. get_permalink() and the_permalink() are the functions that returns the URL of current post, if that is what you want. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, excerpt"
} |
How to change WordPress user ID?
Is this enough to change the user ID? I'm doing this for security purposes, where the administrator has user ID=1 and I want to keep all posts, pages and content.
UPDATE wp_posts SET post_author='1000' WHERE post_author='1';
UPDATE wp_users SET ID = '1000' WHERE ID = '1';
UPDATE wp_usermeta SET user_id = '1000' WHERE user_id = '1';
ALTER TABLE wp_users AUTO_INCREMENT = 1001;
Is there a WordPress function to do it globally? | Why not make a new account for this user which will generate a new database ID. Then delete the user with the ID of 1 and attribute all posts / content to the new user you created for them? Then you don't have to worry about queries or messing up your database. Also, as said before this makes absolutely no sense from a security standpoint as it's pointless. If your client doesn't trust you enough and wants to micromanage the site security they clearly know nothing about, might be time to dump that client. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "users, security, id"
} |
Change Featured Image Size of the Post
When I click on a post it opens up and it is displaying the featured image at the top of the post. The featured image is being displayed as a width of 1024 x 768. This is taking up the whole screen and I want to make this image a lot smaller.
The content is being display by the `the_content()` function which I've read calls `the_post_thumbnail` but how can I set this so that Wordpress displays the Medium image instead of the full size image everytime? | In you WordPress Admin, Go to Settings > Media, here you can set the default size of 'thumbnail','medium' and 'large'.
If you read through the codex page of the_post_thumbnail() you would have found that it has parameters that can be used to fetch a precised size of the image.
>
> the_post_thumbnail(); // without parameter -> 'post-thumbnail'
>
> the_post_thumbnail( 'thumbnail' ); // Thumbnail (default 150px x 150px max)
> the_post_thumbnail( 'medium' ); // Medium resolution (default 300px x 300px max)
> the_post_thumbnail( 'large' ); // Large resolution (default 640px x 640px max)
> the_post_thumbnail( 'full' ); // Full resolution (original size uploaded)
>
> the_post_thumbnail( array(100, 100) ); // Other resolutions
>
So, you can try `the_post_thumbnail( array(100, 100) );` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images"
} |
Order & Orderby Parameters
I am trying to figure out what the orderby parameter is for "newest" post author.
<
I want to order users by authors who posted the newest posts (post date).
What would be the parameter for that?
Thanks! | Hi for me fast solution is to use custom query
for eg.
$sql="SELECT
`wp_users`.`ID`
, `wp_users`.`user_login`
, `wp_users`.`user_pass`
, `wp_users`.`user_nicename`
, `wp_users`.`user_email`
, `wp_users`.`user_url`
, `wp_users`.`user_registered`
, `wp_users`.`user_activation_key`
, `wp_users`.`user_status`
, `wp_users`.`display_name`
, `wp_posts`.`post_date`
FROM
`wp_users`
LEFT JOIN `wp_posts`
ON (`wp_users`.`ID` = `wp_posts`.`post_author`)
GROUP BY `wp_users`.`ID`
ORDER BY `wp_posts`.`post_date` DESC;";
global $wpdb;
$results=$wpdb->get_results($sql);
foreach($results as $result) {
echo $result->ID; //and so on
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "parameter"
} |
How to implement theme shortcodes in text outside of pages?
I am working on a project where the admin can enter text that will be presented in a custom template. Once the text is written it is saved to the dB then pulled out and presented when needed.
The problem is that the theme we are using uses shortcodes for some of the design elements. So when the shortcodes are used in this text, and the text is 'echoed' back, the shortcodes are ignored.
Is there someway to pre-process the text so WP will insert the shortcodes?
These shortcodes are not mine, they are from the theme, so the text needs to recognize and activate these shortcodes. | You can run the text through `do_shortcode`:
echo do_shortcode( $your_text_with_shortcodes );
or you can apply `the_content` filters to the text, which does the same thing as above along with some additional formatting goodies, like auto paragraphs and texturize:
echo apply_filters('the_content', $your_text_with_shortcodes); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Disabling outbound connectivity on web servers
Is it a good idea to harden your web server by disabling outbound connectivity on them?
I am using RHEL 7 for a WordPress Multisite installation.
After disabling outbound connectivity, the dashboard has become extremely slow, and the plugins page does not list the latest available ones.
Could I still live with this? What are the biggest disadvantages? | WordPress uses an HTTP class to make outbound requests. These requests are mainly for plugin, themes and core updates; pull news/rss content; and make third party API requests.
There may be many different reasons for disabling outbound requests, security is the primary one. A WP instance with disabled outbound requests is more secure. Many institutions have intranets or secure networks that do not allow external requests. If the outbound requests are not disabled within WP, then WP admin console will not function properly due to timeouts.
The main disadvantage of blocking outboud requests is blocking third party APIs or any external requests. There are many plugins that will not function if you do so.
If you want to disable WP from making any outbound requests add these settings in wp-config.php: ` define('WP_HTTP_BLOCK_EXTERNAL', true); // block external requests define('DISABLE_WP_CRON', 'true'); // block WP cron ` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "multisite, security"
} |
Change CSS when user is logged in
So I have the following code:
<h3>
<div class="sellertitle"><a class="allseller" href="#">Something</a> </div>
<?php if ( is_user_logged_in() ) { ?>
<div class="otherseller"> <a class="allotherseller" href="#">Else</a> </div>
<?php } ?>
</h3>
Then, for the "sellertitle," I have the following CSS:
<--logged in-->
.sellertitle {
float: left;
width: 49%;
}
As you can see, "Something" is always visible and "Else" is only visible when the user is logged in.
However when the user is logged out, I want the "sellertitle" CSS to be "float:none"
<--logged out-->
.sellertitle {
float: none;
width: 49%;
}
What would be the best way to achieve this? | Here is another CSS-only approach, without any inline-PHP and needless CSS-spam in the head. If your theme is correctly using body_class() and a user is logged in, Wordpress adds a class "logged-in" to the body-element, so we can use this in our stylesheet:
<--logged out-->
.sellertitle {
float: none;
width: 49%;
}
.otherseller {
display: none;
}
<--logged in-->
.logged-in .sellertitle {
float: left;
}
.logged-in .otherseller {
display: inline;
} | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 3,
"tags": "css"
} |
How Can I Use a Custom AccessFileName?
I have a need to have a custom `AccessFileName` setting in my virtual hosts, however it appears that `save_mod_rewrite_rules` function assumes that `.htaccess` is the name for everyone.
How can I override that function safely? | Unfortunately no.
The filename is hard-coded into the core WordPress function with no way to override it by way of filters or other hooks. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, htaccess"
} |
Adding a class to shortcode API
So, I have the following shortcode which is included in two different pages.
<?php echo do_shortcode('[shortcode]'); ?>
Since two pages are using one identical shortocode, I am thinking of adding a class to the first page so that I can customize the first page shortcode only.
So here is my question.
1. Do you think that adding a class to the shortcode in the first page would allow me to customize it?
2. If so, what is the proper way of adding a class to the above code?
3. If not, what would be an option to add customization to a shortcode for only specific page?
Thank | If it really is just for one page you could use a conditional on `the_ID();` from within your shortcode class (it is a custom shortcode right?)
$class = the_ID() == 213 ? "some-other-class" : "";
$myhtml = sprintf("<div class='some-class %1$s'>%2$s</div>",
$class,
$content);
The other option is to add parameters or "attributes" to your shortcode as in the codex. See: <
Hope that helps. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortcode"
} |
Which is the recommended method to transfer a wordpress site to wordpress Multisite?
I want to create a wordpress site on my local server and then trasfer it into another server that runs a wordpress multisite installation.
Which way is safer to follow:
a) install a wordpress single installation in my local server and after development export it and import it to the wordpress MU which already has a blank site and the theme and plugins installed
b) install a wordpress MU installation in my local server and after development export the specific site and import it to wordpress MU which already has a blank site and the theme and plugins installed
Is any of the above recommended or both are the same?
P.S: the requirements say that WP version has to be 3.6.1 | Using the WordPress XML export doesn't work in every case. Especially if you have to deal with plugins.
I had the best results if I first installed the theme and all plugins in the network, created a new site, activated theme and plugins (in case they create data base tables) and then import the WordPress XML.
For NextGenGallery it didn't work, though. I had to copy all images and the data base tables manually. The path for each image needs to be mended with search and replace, since in the network installation you'll use blogs.dir/<number>/ for uploads. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "multisite, migration"
} |
Multisite "Skip Confirmation Email" Log Out Problem
I have a multisite setup where I would like site Administrators to be able to add New Users with the Skip Notification Email option.
By default, Wordpress only allows Super Administrators this privilege in a multisite setup. I have used the code below to fix this problem except it logs the Administrator out after each New User is added. I have tried removing the redirect line but the administrators are still being logged out.
function your_disable_activation( $user, $user_email, $key, $meta = '' ) {
// Activate the user
$user_id = wpmu_activate_signup( $key );
wp_set_auth_cookie( $user_id, true, is_ssl() );
wp_redirect( /*redirect to */ site_url() );
exit;
}
add_filter( 'wpmu_signup_user_notification', 'your_disable_activation', 10, 4 );
How can I run this code (or similar code) without the Administrator being logged out each time?
Thanks! | Update: I've got it working now! It still shows a text box that says the User email must be confirmed, but it DOES create the user regardless of that information. Here is the code I have used:
function your_disable_activation( $user, $user_email, $key, $meta = '' ) {
// Activate the user
$user_id = wpmu_activate_signup( $key );
wp_redirect( /*redirect to */ site_url() );
return false;
}
add_filter( 'wpmu_signup_user_notification', 'your_disable_activation', 10, 4 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, users, user registration, signup"
} |
Add a wp editor to custom plugin and save data
I'm creating a custom plugin. One of the fields in the plugin let's the user add data.
If I add a `textarea` the user has no control over the text. So I would like to add a editor.
I know WordPress offers the `wp_editor();` function.
After some Google-ing I found that it is very easy to implement the editor.:
$content = '';
$editor_id = 'mycustomeditor';
wp_editor( $content, $editor_id );
This shows a nice editor. The problem is that the content isn't getting saved.
The editor is a part of a form so I thought I add the save function to the form save function like this:
`if( isset( $_POST[ 'mycustomeditor' ] ) ) {update_post_meta( $post_id, 'mycustomeditor', array_map('sanitize_text_field', $_POST[ 'mycustomeditor' ]) );} ` However WordPress thinks different about this. It does create the `meta_key` in the database but no value.
I hope anyone can see what I'm doing wrong! | Solved it!
Hope somebody else can use it or it answers their problem. If there is a better way please share and tell why.
$editor_id = 'custom_editor_box';
$uploaded_csv = get_post_meta( $post->ID, 'custom_editor_box', true);
wp_editor( $uploaded_csv, $editor_id );
To save the data:
function save_wp_editor_fields(){
global $post;
update_post_meta($post->ID, 'custom_editor_box', $_POST['custom_editor_box']);
}
add_action( 'save_post', 'save_wp_editor_fields' );
And that's all there is to it! | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "php, wp editor, customization"
} |
Display posts from catagories
I am using an option framework. This saves catagory ids.To get ids I have done
$cat = $atts['post_catagory'];
var_dump($cat);
The var dump result is
`array (size=2) 0 => string '1' (length=1) 1 => string '15' (length=2)`
Here 1 and 15 are catagory ids. To query posts I have used
$args = array( 'orderby'=> ASC,'cat'=>$cat);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
the_title( '<h2 class="entry-title"><a href="' . get_permalink() . '"
title="'.the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a></h2>' );
endforeach;
But I got error. Also can do the same query using wp_query? Thanks | `cat` needs to be an `int` or `string`, and you are passing an `array`. Either use `category__in` instead, which accepts an array, or convert `$cat` to a string of values with `implode(',', $cat)` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, get posts"
} |
WordPress Translations
I've just recently learned about .po and .mo files in WordPress Themes. My question is, are these files supposed to be used to translate page and post content or just the WordPress backend along with Plugins? | .po and .mo files are for translating strings in code files. For translating post content use a translation plugin. I've used a few and find WPML to be the best in many aspects.
Incidentally, they have a built-in workflow for translating both content and strings in code files. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation, localization"
} |
Child Theme Fatal Error
I wanted to create a child theme on my new Wordpress site.
I followed the instructions on the first part of this site: <
After doing everything AFTER "How to Create a Child Theme" and before "Template Files", I'm getting the following error message:
**Fatal error:** Cannot redeclare twentyfifteen_widgets_init() (previously declared in /home/username/public_html/wp-content/themes/twentyfifteen-child/functions.php:142) in **/home/username/public_html/wp-content/themes/twentyfifteen/functions.php** on line **141**
(Here, I'm replacing my actual username with the word "username")
I'm not sure really where to start. I followed the directions to a T and am even using the same theme... | Your child theme's `functions.php` file should be an empty file to which you can add code specific to your child theme. It appears you have copied the `functions.php` file from the parent theme instead.
See this note about `functions.php` in Child Themes:
> Unlike style.css, the functions.php of a child theme does not override its counterpart from the parent. Instead, it is **loaded in addition to the parent’s functions.php**. (Specifically, it is loaded right before the parent’s file.) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "errors, child theme"
} |
Button linking to an unique link
Here is the PHP that I have which i am trying to change:
global $current_user, $post, $product;
?>
<?php if ( $post->post_author == get_current_user_id() ) { ?>
<div class="wpproductedit">
<p class="wpproducteditbutton"><a href="
</div>
<?php } ?>
Here, the button only takes the user (author of the product) to product page which then they have to find the product they want to edit.
So any product edit page will have the following URL:
As you can see, only the product name changes.
In summary, I am trying to edit the "Edit" link so that it will be like the following and picks up the product name automatically.
| If I understand your question correctly, I think what you are looking for is `edit_post_link();`
To use it just insert `<?php edit_post_link(); ?>` into your theme. This will output a edit link leading to the current page/posts editor.
**Update after rewrite of question:**
You can replace your link with the following to include the posts slug in the url.
`<a href=" echo $post->post_name; ?>/edit">`
You might want to look into also replacing the hardcoded link < with a more generic like `home_url();`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "links"
} |
Next/Previous post navigation
Hey guys i want to make my next and previous links to work just for a category not all of them togheter,so when you get on the last post from that category to stop,right now it's still going in another category,can't fine the post_nav_link in my single.php....can you help me ? Here's a photo of my single.php!single.php
Sorry for my bad english,thanks. | looks like your navigation can be found in this function:
sixteen_content_nav()
I just guess, but have a look into this file: inc/template-tags.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, next post link"
} |
Why I can not modify the appereance of my title web site in google?
I have tried everithing I have thought, but I could not solve it. The problem is that when I search my website domain in Google it appears like this: !My title website in Google
Which is different that the tittle I have configured with the plugin Wordpress SEO by Yoast: !My title website in Yoast configuration
I would like to know why I can not change this title. | You can’t force Google to use your `title`, they may change it in their SERPs:
> […] we have algorithms that generate alternative titles […]
> Google's generation of page titles and descriptions (or "snippets") is completely automated and takes into account both the content of a page as well as references to it that appear on the web. […] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "title, seo, plugin wp seo yoast"
} |
Avoiding "Usage of a direct database call is discouraged"
WordPress-Coding-Standards reports that _"Usage of a direct database call is discouraged."_
It's complaining about my usage of `$wpdb->insert()` in a plugin. Is this not recommended? What is the correct way to insert data into a plugin's database table?
Or can I just ignore this error? In which case, is there some system to mark it as reviewed and not to be flagged again? | Using `$wpdb->insert` and or related methods to modify data within any of the default WordPress tables, be it **posts, postmeta, user, usermeta** etc is discouraged because there are functions which already exist for the purpose of modififying data within those tables.
For example,
* `wp_insert_post`
* `wp_update_post`
* `wp_delete_post`
## Database Queries
> Avoid touching the database directly. If there is a defined function that can get the data you need, use it. Database abstraction (using functions instead of queries) helps keep your code forward-compatible and, in cases where results are cached in memory, it can be many times faster.
>
> <
However **it is acceptable** to use the `wpdb` class on custom tables for which no function wrappers exist for the purpose in which you need.
You can try adding a comment on the line of the query:
$wpdb->insert() //db call ok
$wpdb->insert() //db call ok; no-cache ok | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "wpdb, coding standards"
} |
Next post in category
i tried to make my previous/next to move only for one category,but i can't seen to make it work... < this is a pastebin of my template-tags.php where i have my next_post_link code. Here's a short version of the code :
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-nav">' . _x( '←', 'Previous post link', 'sixteen' ) . '</span> %title' ); ?>
<?php next_post_link( '<div class="nav-next">%link</div>', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'sixteen' ) . '</span>' ); ?> | You should be able to just use the default get_next_post_link with $in_same_term set to true. Have you tried that?
* * *
Instead of your
<?php next_post_link( '<div class="nav-next">%link</div>', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'sixteen' ) . '</span>' ); ?>
try this
<?php next_post_link ( '%link →', '%title', true, '', 'category' ); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes, next post link"
} |
WP_Query sort by comment meta data
Is it possible to use the `WP_Query` class to order by comments meta data fields? | I solved my problem by adding a hook on the action `wp_insert_comment`.
When my hook is called i calculate the average rating for each rating meta-tag of my comments. Then i add a meta tag to the post with the result
I can use the post meta-tag to sort with `wp-query` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "wp query, comments, order"
} |
How to get attachment id as soon as it is uploaded through media uploader in jquery?
Using jquery, I am trying to get image attachment id of all images requested to upload through media uploader on post edit page or upload.php. Here is what I tried but this works after all images are uploaded:
if (typeof wp.Uploader !== 'undefined' && typeof wp.Uploader.queue !== 'undefined') {
wp.Uploader.queue.on('reset', function() {
console.log('images uploaded!');
});
}
How can achieve the same? Thanks | You are close, you just need to hook into the `add` event instead of the `reset` event. (In case you did not know, these are standard events provided by Backbone collections. So familiarizing yourself with that will be helpful when developing things around stuff where WordPress employs Backbone.js.)
So basically you'd modify your code like this:
if (typeof wp.Uploader !== 'undefined' && typeof wp.Uploader.queue !== 'undefined') {
wp.Uploader.queue.on('add', function() {
console.log('image uploaded!');
});
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 6,
"tags": "jquery, uploads, javascript, media library"
} |
Sortby parameter to sort users
So for my post list, currently these are sortby `post_count`.
Now, I am trying to sort the posts by "most newest" or "recent"
Here is how the shortcode works
[sortby=post_count]
Other parameters can be found from Order & Orderby Parameters, however I could not find parameter for "most newest."
Any suggestions? | Simply use `date` as a value to `orderby` and `DESC` as value to `order`. This will get posts which was published the most recently. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sort, parameter"
} |
Remove the widgets tab from theme customizer
In some of our sites, I would like the site admins to customize the widgets only on the widget page, and not in the Theme Customizer.
How can I remove the widget tab from there? | you can create function for theme customizer with all the settings you need:
to remove "widgets" we will need to remove the "widgets" panel.
put this code in function.php
function your_customizer( $wp_customize ) {
$wp_customize->remove_panel( 'widgets' );
}
add_action( 'customize_register', 'your_customizer' );
or if you have your own function just add:
$wp_customize->remove_panel( 'widgets' ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "widgets, theme customizer"
} |
Hide text if not homepage
I want to add text but only appear on the homepage only. I have used this if script:
<?php if( is_home() ) : ?>
<p>Some text</p>
<?php endif;?>
but the problem with this is it's appearing on every paginated page. So for example if I view ` it will show that text. I only want it appear on 1st page.
Any fix to this? | You can use `is_paged()`
> ...checks if page being displayed is "paged" and the current page number is greater than one. This is a boolean function, meaning it returns either TRUE or FALSE.
You can adjust your code as follows
<?php if( is_home() && !is_paged() ) : ?>
<p>Some text</p>
<?php endif;?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "customization, pagination, homepage"
} |
Hide sidebar if post_type is in array
I would like to hide the sidebar on certain post types. I can hide it on **one** post type by using:
if ('example' != get_post_type()) {
How could I use the above with an array?
$hide_sidebar = array('example1', 'example2', 'example3'); //hide sidebar on these post types
if( /*post type is not in $hide_sidebar*/ ){
get_sidebar();
} | This is more php, but you can use `in_array()`. Just check if the current post type is in array in `$hide_sidebar`.
You can do the following
$hide_sidebar = array('example1', 'example2', 'example3'); //hide sidebar on these post types
if ( in_array( get_post_type(), $hide_sidebar ) ) {
// Do something if the post type is in array
}
or the negative
$hide_sidebar = array('example1', 'example2', 'example3'); //hide sidebar on these post types
if ( !in_array( get_post_type(), $hide_sidebar ) ) {
// Do something if the post type is not in array
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "array"
} |
How to activate or install the Gallery Widget?
I would like to activate the _Gallery Widget_ which is presented here. It seems that it's part of the general Wordpress distribution but the widget is not listed under **Appearance** → **Widgets**. BTW, I don't see most of the widget present here. I only have the widgets described here.
So, is there a way of installing that widget? Is it a plugin I need to install? Or is the selection of available widget dependent on the Theme?
BTW, I'm using Wordpress 4.1.1. | All of those plugins are only included for wordpress.com hosted websites specifically, and not included by default in a normal WordPress installation. Some of those plugins are available to download through the plugins section of you WordPress install, but I'm not sure if all of them are. For the gallery, try searching here: < there are hundreds of gallery plugins available. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "widgets"
} |
Create various image sizes ad hoc
Im making my theme responsive and hence would like the images to have various sizes depending on device, resolution etc.
Normally i would just add make a add_image_size hook to image upload, however the theme im developing is already in use and the sizes needs to take effect for previous uploaded images aswel.
Is it possible to create the various image sizes ad-hoc? perhaps some hook i dont know about?
Best Regards, and thanks in advance | You could, but I wouldn't recommend doing it on the fly as it would take up unnecessary page resources each time the user loads the page. A better way to do it would put in the add_image_size hook you mentioned into the functions file, then install a plugin to regenerate thumbnails. < I've used this one in the past and worked very well. You should only have to install it, generate the thumbnails once, and then you can uninstall the plugin. The thumbnails should generate on each upload after that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "responsive"
} |
Disable image rename on upload
When I upload an image (`test.jpg`) with the Media manager it creates the same image with a digit after its name (`test1.jpg`).
I disabled image cropping so files like `test-[width]x[height].jpg` don't appear on upload. But I still have duplicates of the images.
So how could I disable this copying and renaming? | The renaming to test1.jpg is not due to any cropping / resizing functions WordPress. This is because you already had a file named test.jpg uploaded, and WordPress does not replace files if one exists in the folder that has the same name. If, for some reason you want it to replace files rather than rename it (not recommended) you can use a plugin like: < and it will not rename your files, it will replace existing files. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, uploads, media, duplicates, cropping"
} |
Can we import Magento products to the Wordpress?
Can we import Magento products to the word press? For example, let just say I have an e-commerce site in Magento and blog is developed in WP. Now I want to pull the Magento customer wishlist products to the word press.
Is there an easy way to implement this? perhaps an extension? so far I couldn't find it. If you could shed some light on this it would be much appreciated. | No. Magento and WordPress are 2 different things. WordPress is a Content Management System (CMS) that allows you to create Pages / posts. Magento is an e-commerce platform that allows you to sell products. There are plenty of e-commerce _plugins_ for WordPress that you can install, and then import your Magento products into the database for that particular plugin. I can't say how, since whatever plugin you choose will have different instructions. The most popular e-commerce plugin for WordPress is WooCommerce < and then you can use this plugin < to migrate your data.
If you want to simply integrate Magento with WordPress so that you can utilize the products from magento in WordPress side-by-side then yes it's probably possible. < you can checkout this plugin to help you do that. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "e commerce, magento"
} |
Displaying Widgets
During theme development, I understand how to create basic widgets within the `functions.php` file.
However, when it comes to displaying the widget within a theme, is there a preferred way to display them - primary, what are the benefits of using the `the_widget()` function versus the `dynamic_sidebar()` function? | `the_widget()` is used to display a specific widget outside of a sidebar. To be honest, this function serves no valuable purpose as you need to hard code the widget `$instance` parameters, this means that you will need to manually change the code every time you need to change something. So much for dynamica. It would just be easier to simply code a custom function and then calling it in your template where needed. It will be faster and much easier to use
Stick with widgets inside sidebars as they are dynamic and can be changed without touching theme or plugin code. I would rather code twenty sidebars and add them in strategic places than using one hardcoded instance of `the_widget()` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "functions, theme development, widgets"
} |
Hook Adding content after title
I need to add something after title in loop in single post and page, home page, categories. This is for a plugin and i don't want to modify the theme directly.
function after_title($title) {
if (!is_admin() || is_single() || is_page() || is_home() || is_category() ) {
$write = 'AFTER TITLE';
$after_title = $title.$write;
return $after_title ;
}
}
add_filter( 'the_title', 'after_title' );
But it add content everywhere, in the widget or sidebare loop and even in my menu. I just want to do it in the main content, not everywhere.
I also tryed other ways but i had the same problems.
add_action('the_post', 'atr_insert');
add_action('the_content', 'atr_insert'); | Use `in_the_loop()` to know if you are currently in the loop of the main query.
function after_title($title) {
if ( in_the_loop() && ( is_single() || is_page() || is_home() || is_category() ) ) {
$write = 'AFTER TITLE';
$title = $title.$write;
}
return $title;
}
add_filter( 'the_title', 'after_title' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "hooks"
} |
If meta_key exists then don't select this post?
I'm trying to select all posts EXCEPT ones with a meta_key `somekey`.
SELECT *
FROM wp_posts JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id
WHERE meta_key != 'somekey'
But this is still selecting that post, because other meta_keys still match.
Basically, the effect I want is to enter a custom field named 'somekey', and then that post will not be selected. | There are a few ways you could do it- `NOT IN`, `NOT EXISTS`, `IS NULL`. Which method is best depends on your actual query.
SELECT *
FROM $wpdb->posts LEFT JOIN $wpdb->postmeta
ON $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->postmeta.meta_key = 'somekey'
WHERE $wpdb->postmeta.post_id IS NULL | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "posts, post meta, mysql, sql"
} |
Display custom widget, added as a shortcode in the correct place
I've created a custom Widget and I would like to add it to the page content as a shortcode.
function show_custom_widget() {
the_widget( 'WP_Custom_Plugin');
}
add_shortcode('custom-widget', 'show_custom_widget');
and I am using my shortcode in the post content as follows
[custom-widget]
As a result I get my Widget but it always displays at the top of the post content not in the place where I used the shortcode. How to make my widget display in the correct place ? | The output from a shortcode should be returned, not echoed. Echoing output in a shortcode will have unexpected output like you are seeing. `the_widget()` echos its output which is causing the issue. Unfortunately there is no similar function for returning the wdget output.
Luckily you can make use of a output buffer to overcome this issue. You can try something like this : ( _CAVEAT: Untested_ )
function show_custom_widget() {
ob_start();
the_widget( 'YOUR CUSTOM WIDGET' );
$contents = ob_get_clean();
return $contents;
}
add_shortcode( 'custom-widget', 'show_custom_widget' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "widgets, shortcode"
} |
Wordpress Admin - Add Edit link to specific page under Pages Menu
I am trying to add direct links to edit specific pages, under the Pages menu:
!Example
Currently I am using, which give me the menu item / link:
add_pages_page( 'Hero', 'Hero', 'read', '15', '' );
However when I click it, the page is blank with the following URL:
edit.php?post_type=page&page=15 | Try
add_action( 'admin_menu', 'wpse182102_register_my_custom_menu_page' );
function wpse182102_register_my_custom_menu_page() {
add_pages_page(null, 'Menu Item Name', 'edit_posts',/* or whatever capability required for this object */ '/post.php?post='.get_page_by_title('Etusivu')->ID.'&action=edit', null, '');
}
And change _Etusivu_ to be the name of the page you want to edit. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "pages, wp admin"
} |
Adding custom field in menu options
Please take a look at this image  and activate **CSS Classes**. Then add `fa-home fa-fw` to your CSS class field. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, custom field, menus, forms"
} |
Nginx rewrite rule conflict with WordPress permalinks rule
Facing issue with nginx url rewrite rules. What I want is to serve < page when someone tries to access < url. And it should return 200 status. I tried below rewrite rule which works fine when wordpress permalink is set to default but as soon as I set permalink to custom below rules does not works.
location ~ ^(.*)/myfeed(.*) {
rewrite ^(.*)/myfeed(.*)$ $1$2 last;
}
Other rule in my nginx conf file is,
location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}
I guess my rule is conflicting with the WordPress custom permalink rule. Can anyone please help with this? | Use this plugin in wordpress and write rule which will overwrite nginx rule.
<
When you have wordpress, you have to set permalink to default to work your webserver rule work and if you dont want to do that you have to install above plugin and write rule. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "url rewriting, rewrite rules, nginx"
} |
Set default Custom Post Meta Value
I've tried almost anything and just can't get this to work.
I have a custom post type with a custom meta field and I want a default value to be added on when the Publish/Update/Save button is pressed.
I tried all kind of hooks `wp_insert_post`, `save_post`, `edit_post`..
add_action('save_post_post_type', 'set_default_meta', 10, 3);
And my function is:
function set_default_meta( $post_ID ) {
$meta_value = get_post_meta($post_ID, 'meta_value', true);
if ( $meta_value == '' && !wp_is_post_revision($post_ID) ) {
add_post_meta( $post_ID, 'meta_value', 0, true );
}
}
When I publish the post, the value is not saved. **However** whenI click View Post, the value is immediately saved.
Any help will be really appreciated! | Use `update_post_meta()`, because if the meta key already exists `add_post_meta()` will do nothing if `$unique` is `true` and otherwise won't update neither, while `update_post_meta()`, well, it will update the value of a existing field or create it, if it doesn't exist yet. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post meta, actions, wp insert post, save post"
} |
Manage Roles and Capabilities on Multi-site
I am trying to enable some features for Subscriber user role in a eCommerce theme where originally had be set for Admin role and I like to modify that. I tried AAM plugin but for this specific site it does not show those features so I can place a check or un-check them. I know AAM or any alike plugin serve as an interface and there are ways to look through the files/codes to make this happen. I found in wp-includes/capabilities.php is where this gets managed but I am assuming not for each specif site as I can't find anything about other sites in there. Does each site have its own capabilities.php somewhere? | I believe you'd need to modify user roles on each site individually (if I'm understanding your question correctly).
There's a great plugin I use frequently called WPFront User Role Editor that allows you to check/uncheck user capabilities like you mentioned. The free version should be fine for what you're trying to do. I personally use the paid version just because I like to have the extra options when I need them, but 90% of the time the free one works fine.
You can view the plugin here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "capabilities, user roles"
} |
Should I use Multi Site to achieve different designs for different sections?
I'm about to start a website where I'll need to have a different "feel" in design, and in information displayed, for each section.
So, for instance, when you go to the "chocolate" section the design has to be brownish overall (pages, posts and archives), and the sidebar should show chocolate-related material. When you go to the "candy" section, it should be a "pink" design with a sidebar displaying info about candy, and so forth...
How can I achieve this? Do I need a Multi-Site installation? Is there a downside to using a Multi-Site install for this purpose? | Multisite isn't really the best option here.
If you need different layouts and styles for, say, the header on different pages, you can use the is_page function to call a different header file depending on which page the user is on.
So to load up a different header on your home page as opposed to any other page, in your index.php (or other page template) add: `if ( is_page('home') ) { echo get_header(home) }`
In this case you'd need a file called "header-home.php" that contains all the necessary code for that custom header, with any classes/id's for items specific to that page so you can style them appropriately.
If you want a quick and easy (but not technically correct) way of doing it, you can just wrap some inline styles in an is_page function, so that those styles are only applied if a user is on that page. But if it were me I'd just load up custom template files to avoid inline styling.
Here's the function reference for is_page() | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
a: hover issue with image issues
I am not sure what is wrong but the navigation a:hover has a image that when you hover over it shows. I am looking to see why there is a small space between the end of the image and slideshow. I am wanting to to butt right up to it where there is no gap.
See test board here
< | This isn't a WordPress issue, although it _IS_ an easy CSS fix.
The small space between the end of image and the slideshow is axtually 2 pixels wide and caused by the `#left-area` div.
You can just up the width by 2 pixels on #left-area. Like this:
#left-area {
width: 639px;
}
It is currently 637px.
You could also up the padding-left by 2 pixels to acheive the same gap closure, although then the slideshow is a little off center.
Hope that helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, css"
} |
parse_tax_query causing Navigation Menu To Disappear
I am using the following snippet to modify a query...
function no_child_terms($query) {
if( !is_admin()) {
$query->tax_query->queries[0]['include_children'] = 0;
}
}
add_action('parse_tax_query', 'no_child_terms');
This is working correctly and it is modifying the query correctly but it is causing my navigation menu to disappear. Am I using parse_tax_query correctly? | Query parsing happens on every query run on a page, not just the main query. Your `parse_tax_query` is modifying the query for menu items in your menu. Check `is_main_query()` to make sure you only change the main query:
function no_child_terms($query) {
if( !is_admin() && $query->is_main_query() ){
$query->tax_query->queries[0]['include_children'] = 0;
}
}
add_action('parse_tax_query', 'no_child_terms'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, menus"
} |
How to use the filter 'widget_text' to a particular text widget with id
I have a sidebar with 10+ text widgets serving advertisements. Now I want to filter a particular text widget in a single post if that post has a data in meta field. I searched a lot and found Is There A Hook To Process The Content Of The Text Widget?. But this changes the content of all text widgets. How can I change a particular text widget? | Is it default text widget? If yes, then I don't think there is a way.
Why don't you create a custom text widget? And before echoing output process the text whatever you wants to do?
The logic is, you will create another widget, that will take some text (or html?) and you will process that text, add some data what you want and show as output :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, widget text"
} |
Use existing image sizes for WooCommerce
I've built a theme and have set the following image dimensions via functions.php:
set_post_thumbnail_size( 1064, 347, true ); // Upload @ 2128(W) x 708(H)
add_image_size( 'standard', 352, 235, true ); // Upload @ 704(W) x 470(H)
add_image_size( 'gallery', 750, 500, true ); // Upload @ 1500(W) x 1000(H)
I use this script to push out 2 versions of the image for retina displays.
I would like to use the image size `'standard'` for my catalog images and `'gallery'` for the single product image.
Is there a way to disable the WooCommerce image sizes via functions.php and use the ones I have already created?
I've tried customising the image sizes via Settings > Products, but it doesn't work with the retina script I'm using. | You have to use `single_product_large_thumbnail_size` filter for Single Product page.
something like:
function custom_product_large_thumbnail_size() {
return 'gallery';
}
add_filter('single_product_large_thumbnail_size', 'custom_product_large_thumbnail_size'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, woocommerce offtopic, images"
} |
Completely remove the author url
I've already removed the login, registration, and password reset stuff. i also removed all links to the author url from single, archive, and index. now i want to remove the actual route so that bots cannot discover the author username. | You can add this to `.htaccess` file, it will redirect all author requests looking for a number ( Author ID ) to the homepage:
#Disable Author Pages
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{QUERY_STRING} ^/?author=([0-9]*) [NC]
RewriteRule ^(.*)$ [L,R=301,NC]
</IfModule>
* * *
The PHP / Wordpress way, you could use Template Redirect:
function author_page_redirect() {
if ( is_author() ) {
wp_redirect( home_url() );
}
}
add_action( 'template_redirect', 'author_page_redirect' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "security"
} |
Adding a space between next and previous post links
i've been struggling with this for a while but i can't seem to make it work.So i wanna add a space between my next and pervious post link right now it looks like this : !enter image description here
Here's a pastebin of my template-tags.php : < Any ideas ? Sorry for my bad english. | You could for example change
`<?php next_post_link ( '%link →', '%title', true, '', 'category' ); ?>`
to `<?php next_post_link ( '<div style="float: right">%link →</div>', '%title', true, '', 'category' ); ?>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, next post link"
} |
Enqueue script on specific WooCommerce template
I would like to enqueue a lightbox script on the WooCommerce page `content-single-product.php`.
I have tried the following via `functions.php`:
if(is_page_template( 'page-gallery.php' ) || is_page_template( 'content-single-product.php' )) {
wp_enqueue_script( 'theme-lightbox', get_template_directory_uri() . '/js/lightbox.js', array(), '20150323', true );
}
The script loads correctly on `page-gallery.php`, but not on the WooCommerce single product page. I assume this method only works for my theme page templates? | You need to delay the firing of your code, otherwise your conditionals will evaluate false (the request won't have been parsed yet). Use the action `wp_enqueue_scripts`:
function wpse_182357_enqueue_scripts() {
// Your code
}
add_action( 'wp_enqueue_scripts', 'wpse_182357_enqueue_scripts' );
Update: Missed the root of the problem - `is_page_template()` only works for pages. Rather than checking if the current template file is `content-single-product.php`, check if the _request_ is for a single product with `is_singular()`:
is_singular( 'product' ); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "wp enqueue script, woocommerce offtopic"
} |
Accessing a protected property of a post
> **Fatal error** : Cannot access protected property Some_Plugin::$_some_property
What is the best/least-destructive way of accessing a protected property attached to a post.
The property is being affixed to the post by a plugin but I need to access it's stored information to display.
The options I can think of are:
1. Altering the plug-in code. I'm not so familiar with Object Oriented PHP so I hesitate to do this to avoid damaging the functionality.
2. Somehow invoke the plug-in so I'm in the correct context to retrieve the information (possibly with function in functions.php)
3. Write a function which hooks to the publishing of this post type and duplicates the information to a new, non-protected property of the post.
Does anyone have any suggestions or code samples illustrating the best way to go about this. If you need more information just comment and I'll update the question.
Thanks! | The foolproof method here to grab a dynamic member variable is to use reflection!
Lets say we have this class:
class MyClass {
private $myProperty = true;
}
We can use reflection to acquire the class, and the property:
$class = new ReflectionClass("MyClass");
$property = $class->getProperty("myProperty");
We can then set that property to accessible:
$property->setAccessible(true);
Now we can access the private member variable using the new `$property` object:
$obj = new MyClass();
echo $property->getValue($obj); // Works
Note, that the member variable is still private if we access it directly:
echo $obj->myProperty; // Error
However your code implies a static member variable, e.g.:
class Some_Plugin
private static $_some_property;
}
Which this may not work for | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, plugins, php, oop, user access"
} |
Wordpress plugin addon
Hey I want to ask a question that maybe sounds stupid but I am new in wp plugin development.
I made a wp plugin that have to do with google maps. I have the basic version thats is free for anyone and i would like to offer especially for the members of my site the opportunity to download some additional features like change the color of the map etc.
So lets suppose that someone isn't a member of my site and download the basic version of the wp plugin and after decide to become a member for having access to the add-ons, how he will be able to load the add-on in wp dashboard without to download the whole plugin. I mean me as a developer how can i do this?
Something like a software that when you have an update you don't need to download the whole program but you download the update and load automatic in the existing program.
Thank you :) | You have several options:
## Additional Plugins
Similar to how Gravity forms works, you have the base plugin which is your standard plugin, then you build additional premium plugins that integrate into it using hooks to add additional functionality
## Enabling functionality
Your standard plugin bundles everything inside it, but disables sections of functionality until they're turned on. Turning them on may be via an API key for example
The payment aspects of each solution are going to be very specific to you and how your business model is going to work, so I won't/can't go in to that. Personally I would recommend the plugins route | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
How to use custom field to search for wordpress post type?
I have a post type in called Publication. I also have few custom field in that post type such as Publication Year, Author...
I want to have a search box with 3 drop-down fields which is All Field, Publication Year, and Author. When user select on All Field, it will search everything all post in this post type, but when user select custom field like Publication Year or Author then it search only that post match with that Publication Year or Author.
I spend 3 days searching on this, but I got no luck so please help to advise me.
Thanks | Using pre_get_posts may work. Can you try something similar to the following and let me know if it meets your needs:
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array( 'post', 'movie' ) );
//Should do some sanitation on $GET too
if(isset($_GET['author'])){ //Change to your field dropdown name
$query->set('meta_key', 'author'); //change to custom field name
$query->set('meta_value', $_GET['author']);
}
else if(isset($_GET['pubyear'])){
$query->set('meta_key', 'pubyear');
$query->set('meta_value', $_GET['pubyear']);
}
}
}
}
add_action('pre_get_posts','search_filter');
UPDATE: May also be better to use `$query->set('meta_query'), array(..)...` depending on your needs | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom field"
} |
I need a standalone script in web root but still have access to the database
I am building a specialized xml output script (can't use the built in export) and I have a file in the web root that I can call from the URL domain.com/myscript.php. However, I need to be able to do wordpress DB calls to get to the data. I have read you can load wp-load.php in the script - will that be enough?
Maybe there is some other (better) way of doing this but wordpress sends headers so I can't output a clean xml file without the wordpress clutter (header footer etc). | You _could_ do that, including `wp-load.php` would bootstrap WordPress and allow you to query the database. I prefer to keep things encapsulated in plugins though, much more portable. You just need to hook early enough to send your own headers, and you can short-circuit the rest of the load process. For example-
function wpd_my_export_script() {
if( isset( $_GET['do_my_export_stuff'] ) ) {
header('Content-Type: application/xml; charset=utf-8');
// do your database stuff
exit;
}
}
add_action( 'wp_loaded', 'wpd_my_export_script' );
Then visiting ` will trigger your code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "xml, wp load.php"
} |
How add built-in textarea in theme development?
How can I add built-in textarea instead simple textarea in Wordpress v4 like when I hit Post -> Add new in theme development? I need to add it to theme options page <
!enter image description here | This is called wp editor, which uses tinymce editor and odds. This editor can be called using `wp_editor` function.
To display it on your options page, use wp_editor(); Like -
$field_value = get_option('a_custom_textarea');
$field_name = 'a_custom_textarea';
wp_editor( $field_value, $field_name );
Ref - < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, themes, theme options"
} |
PHP if url extension action=discussion condition use
I want use some style only for url extension /?action=discussion How can I use it by PHP condition? | You can use PHP get method to process these variables.
<?php if( $_GET['action'] == 'discussion' ) { ?>
It's True.
<?php } else { ?>
It's False.
<?php { ?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -3,
"tags": "plugins, php, functions"
} |
How do I change attachment slug from name to id
I need to change the slug of the attachment post. Currently, it is showing attachment name , I want it to be replaced by id of attachment.
Edit : Thanks to suggestion by TheDeadMedic, I am now seeing urls with their postname changed to id in url (slug of the url.). But somehow it is adding now adding /attachment/ as well to the url right before slug (id). How should I remove this /attachment/ part. | Use the `add_attachment` hook to update the slug after the attachment has been inserted:
function wpse_182454_attachment_id_as_slug( $post_id ) {
if ( get_post_field( 'post_name', $post_id ) != $post_id ) {
wp_update_post(
array(
'ID' => $post_id,
'post_name' => ( string ) $post_id,
)
);
}
}
add_action( 'add_attachment', 'wpse_182454_attachment_id_as_slug' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "url rewriting, attachments, slug"
} |
Is it possible to wp_redirect() to a new tab?
Is it at all possible to set up `wp_redirect()` so that it redirects to a new browser tab? If so, how can it be done? | Nop, its not possible at all with `wp_redirect()`. One have to find other way around to accomplish it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "redirect, wp redirect"
} |
Migration to staging server, pages from other site loading in
I'm not really sure how this could happen, but i migrated a wordpress site to a staging server where i have many wordpress sites hosted, everything seemed to go smooth with the exception that all inner pages (not the home page) load a single page from a previous site that is currently hosted on the staging server. Both sites have completely different directories, and their own database tables, and the urls for the inner pages reflect the correct location, yet it is still loading in pages and content from this other site. I'm stumped on how to debug this, and any help is appreciated. | You should use some migration plugin, e. g. Migrate DB, because some file paths and URLs are serialized in database and it's not enough to change just `siteurl` and `home`. `Migrate DB` seamlessly do the job. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "migration"
} |
Does WordPress refer to any files outside of the main install folder (and database)?
Meaning, if I install WordPress in the /wp folder... would any files in the main root of the domain folder "/" be accessed, or any other folder outside of the /wp folder for that matter? Meaning, are all of the WordPress files continuously self-contained to just the install folder (/wp in my case) and it's subfolders?
(Thus, if this is true, to remove WordPress, can we just delete the install folder...and vice-versa, if we install into a particular folder, we know no other files/folder would be affected?)
Thank you! | The short answer is **no** , WordPress does not refer to any files outside of the main install folder. When WordPress loads (via /wp-load.php), it sets the constant `ABSPATH` to the current directory path and points all further includes relative to that.
However, since you are asking, there are some notable special cases:
* If you install WP in its own directory, you have to copy the `index.php` and `.htaccess` file outside the WP directory to the parent directory.
* WordPress checks if `wp-config.php` exists in its parent directory so you could also have that one outside of the main directory.
* The wp-content, plugins, uploads and theme directory can be moved to pretty much anywhere.
These are all options and not default behavior. So the answer remains no. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "directory, installation"
} |
Remove URL from Tag
I've searched Google and I can't seem to find what I hope to achieve. I'm trying to display the tags without the hyperlink, that is this:
`<a href="blalblalba.com/tag/tagname/">tagname</a>`
becomes this:
`tagname`
Is this even possible? | get_the_tags codex page says
> The following example displays the tag name of each tag assigned to the post (this is like using the_tags(), but without linking each tag to the tag view, and using spaces instead of commas):
<?php $posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
} ?>
ever tried that? :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "tags"
} |
How to change default width parameter of embedded video in wordpress?
I am using embedded video short code of Wordpress for showing video in the content of a post
`[embed width="600" height="456"]
and the rendered html is
`<iframe width="600" height="338" src=" frameborder="0" allowfullscreen=""></iframe>`
I found it really nice and cool. It works great.
The only problem is video is not responsive because this takes width in px.
Is there any way to change the width parameter from px to % like 100% ? | if you could make it to something like this:
<div class="videoWrapper">
<iframe width="600" height="338" src=" frameborder="0" allowfullscreen=""></iframe>
</div>
then responsive css for that would be like this:
.videoWrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
}
.videoWrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
if you have no control on the markup, then what we can do is when you put that shortcode in the editor, add some div around it like this:
<div class="videoWrapper">
[embed width="600" height="456"]
</div> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "oembed"
} |
Show posts on front page only
I have a carousel that I want to be posted on the front page only but for some reason the code is not working.
The conditional statement
<?php if ( is_home() ) : ?>
<div class="hero">
<div class="hero-carousel">
<?php
$catquery = new WP_Query( 'category_name=feature&cat=1&posts_per_page=5' );
while($catquery->have_posts()) : $catquery->the_post();
?>
<article>
<?php the_post_thumbnail(); ?>
</article>
<?php endwhile; ?>
</div>
</div>
<?php endif; ?> | The `is_home()` conditional tag applies to the posts page according to your reading settings or home.php file as opposed to the `is_front_page()` conditional which applies to the page on front according to your reading settings or your front-page.php file, if it exists.
Try changing `is_home()` to `is_front_page()`
As for another possible problem might be, take a look at your query arguments
$catquery = new WP_Query( 'category_name=feature&cat=1&posts_per_page=5' );
You are using `category_name` and `cat` together in one argument. You cannot do that. You have to use one or the other. So you either have to remove the `category_name` parameter or the `cat` parameter | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, categories, frontpage"
} |
How to display multiple images in custom field
I'm using a plugin called Anonymous Pro that allows users to submit posts. Users can also submit multiple images into a post, which gets placed in a custom field, like so:
Array ( [0] => )
How would I then display the above images on the frontend? | Assuming we are viewing some king of single - post, page, custom post type etc.
<?php
$imgs_meta = get_post_meta( get_the_ID(), 'AP_post_image', true );
if ( '' != $imgs_meta ) {
$imgs = explode( ',', $imgs_meta );
foreach ( $imgs as $src )
printf( '<img src="%s" />', esc_url( $src ) );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, images"
} |
How do I create settings only used by my theme?
I have a theme that when installed will check to see if the necessary pages are there and if not they will be created (this is for a website not a blog). I'm trying to create settings that will be updated from false to true once each page has been created so that functions.php isn't continuously checking the page's existence.
I've looked into global variables (which is advised against) and register_setting which requires a form. I don't want settings that are visible or can be modified manually but only by the code. | You don't have to register_settigs, you can just add the options straight to the database with `add_option()`.
You could have like a dummy option "all_pages_created" and if that's set then don't check for the individual pages.
if (get_option('all_pages_created') !== false) {
// it's set, do nothing }
else { // check for your pages and update individual_pages_option with update_option()
// and when all pages are created add_option('all_pages_created', 'true', '', 'yes' )
}
Or something like that. It shouldn't be too hard... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "options, variables"
} |
Getting headers property from WP_Theme object
Using `wp_get_theme` returns an object holding the properties of the current theme. The `headers` property contains any array of information I wish to access.
I can access the other properties using normal notation
wp_get_theme()->theme_root
When I try
wp_get_theme()->headers
I get `NULL`
How can I access the array within the `headers` property? Below is a `var_dump` of `wp_get_theme()`
object(WP_Theme)#381 (11) {
["theme_root":"WP_Theme":private]=>
string(14) "/path/to/theme"
["headers":"WP_Theme":private]=>
array(11) {
["Name"]=>
string(9) "Site Name"
["ThemeURI"]=>
string(0) ""
["Description"]=>
string(11) "Description"
...
}
["headers_sanitized":"WP_Theme":private]=>
NULL`
... | You cannot access the `$headers` property as it is a private property.
> Members declared as private may only be accessed by the class that defines the member
For that reason, you get `NULL` when you try to access the property with `wp_get_theme()->headers`. You need to make use of the magic `__get()` method of the class to get the info you are after.
Example: ( _From the codex page,`wp_get_theme()`_)
<?php
$my_theme = wp_get_theme();
echo $my_theme->get( 'TextDomain' );
echo $my_theme->get( 'ThemeURI' );
?> | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "themes, oop"
} |
Allow editors access to added plugins
I created a custom plugin which i want Users who are Editors to be able to use the plugin.
I found a link here to allow access for editors to allow editors to edit menusallow editors to edit menus?
using this code.
$role_object = get_role( 'editor' );
// add $cap capability to this role object
$role_object->add_cap( 'edit_theme_options' );
So, is there a possible way i can allow Editors access to my custom added plugins | Please add the following code.
function activate_plugin_name() {
$role = get_role( 'editor' );
$role->add_cap( 'manage_options' ); // capability
}
// Register our activation hook
register_activation_hook( __FILE__, 'activate_plugin_name' );
function deactivate_plugin_name() {
$role = get_role( 'editor' );
$role->remove_cap( 'manage_options' ); // capability
}
// Register our de-activation hook
register_deactivation_hook( __FILE__, 'deactivate_plugin_name' );`
Refer my tutorial for further explanation. < | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "user roles, editor"
} |
Use a template file for a specific url without creating a page
I wonder if its possible to use a template file for a specific url without having to create a page for that template.
This is my simplified problem:
I have created a page in WP with some link content that points to a specific url with some trailing form data: _(mysite.com/retail/?a=test &b=1234)_.
I want that url (retail) to automatically use my template file template-retail.php that I have in the child theme directory, without having to create a page named ”retail” & select the template page from there. There is only external content in the template-retail.php file, nothing from Wordpress itself.
Is this possible? | You can just look at url, load the file and exit.
That can be done when WordPress loaded its environment, e.g. on `'init'`.
add_action('init', function() {
$url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/');
if ( $url_path === 'retail' ) {
// load the file if exists
$load = locate_template('template-retail.php', true);
if ($load) {
exit(); // just exit if template was found and loaded
}
}
});
Note that doing so a _real_ page with slug "retail" can never be used.
This is pretty easy, but also hardcoded, so if you need this for a single page it's fine. If you need to control more urls, have a look to the solution proposed in this answer. | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 22,
"tags": "url rewriting, urls, page template"
} |
Remove_action from plugin with a Class
I've searched around but haven't been able to find a solution to this. I'm trying to hook in and remove an action that was initiated by a plugin (specifically the Groups plugin). The function itself is contained within a class in the plugin. It basically breaks down like this
class Groups_Registered {
...
public static function init() {
add_action( 'user_register', array( __CLASS__, 'user_register' ) );
}
...
}
Groups_Registered::init();
I've tried to just remove the action, referring back to the class, but it doesn't seem to be working. I've added this to my functions.php file, but it is not removing the action. A
remove_action( 'user_register', array( Groups_Registered::init(), 'user_register' ) );
Anyone know how to solve? I've seen some solutions out there but none of them seem to work. | Just match the callback in your remove call - `array( CLASSNAME, METHOD )`:
remove_action( 'user_register', array( 'Groups_Registered', 'user_register' ) ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, actions"
} |
Selecting NULL value from the database
I have a database with columns that are allowed to be NULL.
Whenever I run a query against this database using `$wpdb->get_results` the columns that are NULL are always returned with an actual value; the number zero.
In my database NULL and zero actually have totally different meanings and I would like to be able to get the correct values from the database without Wordpress translating the returned value.
How can I select from the database so that NULL values are maintained? | There is no specific issue with retrieving null values from the database. They will come back as the PHP NULL value.
WordPress uses either the function `mysqli_fetch_object` or `mysql_fetch_object` to retrieve results from the database.
< <
According to those respective pages:
> Note: This function sets NULL fields to the PHP NULL value.
Are you using `is_null()` to check for the value? Or are you comparing the result to the NULL constant using the identity check (`===`)? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, select"
} |
How to preview your website without the top WordPress admin bar, but remain signed in?
Is there a way to preview your website without the top WordPress admin bar, but remain signed in?
Basically, want to continue making changes in the panel and review the site, but without the top admin bar...but don't want to sign in every time. I don't want to remove the top bar...just don't want it there when I preview my changes, if that makes sense. When working with the top header, I want to see it as users will see it.
Thank you! | OR you can go into your own user profile (hover over your name on the right end of the bar and click on Edit My Profile) and uncheck the box that says Show Toolbar when viewing site. Click Update Profile at the bottom of the page and the bar will go away.
Reverse the process when you want to bring it back. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "admin bar, previews"
} |
Check If post id exist in custom post type , outside of loop
How can I search in database if id exist in a post type?. I want to search `$id=123` in post type 'movies' like this, is this the correct way to do it?
$content = get_posts('post_type=movies&id=$id');
if ($content)
echo "post id exist";
else
echo "post id doesn't exist"; | You can use:
echo 'movie' === get_post_type( 123 ) ? 'Yes' : 'No';
But if you need to check it many times in your theme, you might consider defining your own helper function:
if( ! function_exists( 'is_movie' ) )
{
function is_movie( $mixed = null )
{
return 'movie' === get_post_type( $mixed );
}
}
It might return true when `$mixed` is empty, `\WP_Post` object or a post ID.
So if you want to know if there exists a _movie_ with ID `123`:
echo is_movie( 123 ) ? 'Yes' : 'No';
or just `is_move()` within the loop, to check the current post ID.
If you only need to check if the ID `123` exists, then just use `get_post()`.
For example:
echo is_null( get_post( 123 ) ) ? 'No' : 'Yes'; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "post type"
} |
Can XMLRPC set show_on_front/page_on_front?
Is it possible to set **show_on_front** and **page_on_front** via XMLRPC? They do not appear in the list returned from wp.getOptions and using wp.setOptions does not appear to change the values. | These options are not among the default writable `$blog_options`.
Here's one (untested) idea using the `xmlrpc_blog_options` filter to make the `show_on_front` option writeable:
/**
* Add 'show_on_front' to the list of XML-RPC writeable options.
*/
add_filter( 'xmlrpc_blog_options', function( $blog_options )
{
if( is_array( $blog_options ) )
{
$blog_options['show_on_front'] = array(
'desc' => __( 'Show on front' ),
'readonly' => false,
'option' => 'show_on_front'
);
}
return $blog_options;
});
and similar for the `page_on_front` option. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "xml rpc"
} |
All of my wordpress sites showing †Ù¥
This morning I was going to keep working on my Wordpress page, then when I put in the domain name it only showed this: †Ù¥
I then checked my other sites who I hadn't touched in a while and they also showed this error. I contacted the hosting provider but they don't know what the problem is since the wordpress sites on other accounts work just fine. When I do a fresh install it's alright but all the existing sites show these characters. I think it's a database error. Other sites hosted on my account which do not use wordpress do not have this problem.
My question is, how do I resolve this?
An example of a site I have running on wordpress but displays: <
Hoping for the best!
Best regards, Steve | Somehow your files get broken. It can be UTF8 encoding problem, hacker attack, broken plugin. It's difficult to say what happend without checking your files and log.
I recommend you to **backing up all files &database** , deactivate all plugins and themes and update manually by following this guide : codex.wordpress.org/Updating_WordPress#Manual_Update | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "errors, encoding"
} |
Most popular post for last 7 days
I need to change the most popular post widgets with date restrictions.
For an example, how should I get most popular posts(post_views_count) of last 7 days.
original query,
$popularposts = new WP_Query('showposts=10&meta_key=post_views_count&orderby=meta_value_num&order=DESC&ignore_sticky_posts=1')
then I changed that to,
$args = array(
'date_query' => array( array( 'after' => '-7 days' ) ),
'showposts' => 10,
'ignore_sticky_posts' => 1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$the_query = new WP_Query( $args );
However it doesn't give any results. How should I achieve this?
Thanks in advance. | The correct syntax to get posts from the last week is `1 week ago`. Just another note, `showposts` is replaced in favor of `posts_per_page`. Apart from that, your query should work. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query, popular posts"
} |
WooCommerce -> wc_enqueue_js not working
I have a plugin that was using a deprecated function **add_inline_js**.
I've changed it for **wc_enqueue_js** but it's not working. What I'm doing wrong?
$woocommerce->wc_enqueue_js(
file_get_contents( WOO_CK_PATH . 'panel.js' )
);
Fatal error: Call to undefined method WooCommerce::wc_enqueue_js() | `wc_enqueue_js` is not `method` of `$woocommerce` object.
Just call the function.
wc_enqueue_js( file_get_contents( WOO_CK_PATH . 'panel.js' ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, woocommerce offtopic"
} |
Retrieve contents/page names of various pages for use in a plugin
I'm trying to design a plugin that retrieves the contents of user selected pages and copy the contents into a giant single page. (As long single page websites are trendy right now)
These are the following functions I need to either find or build:
* Get list of page names in database.
* Get contents of the page with page name as the argument.
The pages I am talking about are the user edited pages in the `pages` section of the WordPress.
I'm hoping functions such as these are already apart of WordPress.
I did search WordPress Dev however I couldn't find anything appropriate.
EDIT: I found `get_page()` however the function is now deprecated with the recommendation to use `get_post()`. However does this still work for pages? I thought that a page and post were logically separate entities, for example a different page and post could both share the same ID. Or am I wrong about that? | You can use
* `get_pages()`; or
* `get_posts()`; or
* `WP_Query`
to get a list of pages. They differ somewhat in details, so read up on that. But generally all of them should suffice, for you to achieve your goal. Just choose the best fitting one for your purpose.
For getting pages by name or better `title` you can use:
* `get_page_by_title()`
Or use:
* `get_post()`
if you decide to use the `ID` or the post object.
To save the user selection you probably want to make use of the Options API. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, functions"
} |
How can I bulk delete media and attachments using WP-CLI?
I'm trying to mass delete 4000 images in a wordpress website. WP itself sets the max to 999, which would work fine and take a few minutes to delete them via the backend. However, I get REQUEST URI TOO LARGE because the backend form uses GET instead of POST.
How can I use WP-CLI to perform the operation if it's possible and ensure the integrity of the WP database. In other words, I don't want to run an SQL command. | From the WP-CLI documentation about `wp post delete`:
wp post delete --force $(wp post list --post_type='attachment' --format=ids)
See `wp post list` for additional information. | stackexchange-wordpress | {
"answer_score": 24,
"question_score": 9,
"tags": "attachments, media, media library, wp cli"
} |
Do define() statements need phpDocumentor-style docblocks?
There's no word on this in the WordPress Documentation Standards, but do `define()` statements need phpDocumentor-style docblocks?
/**
* Should this docblock be here?
*
* @since 1.0.0
*/
define( 'MY_CONST', 'Hello' );
// Or would a comment be more appropriate?
define( 'MY_CONST', 'Hello' );
For reference, the list of elements to be dockblock'd that are mentioned in the standards document are:
* Functions and class methods
* Classes
* Class properties
* Requires and includes
* Hooks (actions and filters)
* Inline comments
* File headers
* Constants | I would say the section Constants in the Wordpress: PHP Documentation Standards is pretty clear. It should look like this:
/**
* Summary.
*
* @since x.x.x (if available)
* @var type $var Description.
*/
define( 'MY_CONST', 'Hello' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "documentation, coding standards"
} |
403 forbidden on one page only
I can't access < The only error i get is
> Forbidden You don't have permission to access /biljke/ on this server.
This is regular hierarchical category for post. I have tried:
1. deactivating all plugins (removed category slug also, so url should be < but it still redirects me to < ).
2. I have deleted htaccess file and refreshed the permalinks so Wordpress can generate default one.
3. I have uploaded empty functions.php
4. If I change the slug of category to something else (biljke1) it works, but it won't make sense so I can't let it be.
What else can I try to find out what is the cause of this problem? It is driving me nuts. | Does the folder 'biljke' exist on the server by any chance?? i.e. do you have wp-admin, wp-content, wp-includes AND biljke as folders in your Wordpress root?
[Reposted as an answer so it can be accepted, probably should have done that in the first place without trying to comment!] | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, slug"
} |
Woocommerce: deleted single-product.php, everything still works. How is it possible?
I'm trying to customize `single-product.php` to achieve the often requested **different categories = different single product templates** , but it seems this file it's not affecting anything at all.
It's like only `content-single-product.php` is doing what it should _(eg. if i customize it, the changes are reflected in the single product pages_ ) and the other files are useless in rendering the single products (!).
I even completely delete all php files in `plugins/woocommerce/templates` folder, and if i leave there **only** `content-single-product.php`, everything still works and every single product is correctly shown!
What am i missing about woocommerce's logic?! | This was happening because of a `woocommerce.php` file in theme's root folder, that was overriding a lot of stuff, including `single-product.php`, via `woocommerce_content()` function.
As redelshaap and woocommerce's documentation say, this is not the best way to implement theme compatibility and customization...
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, themes, woocommerce offtopic"
} |
Disable pagination on frontpage
My home page is being build on **index.php**. I have a wordpress loop somewhere there, because I want to show the two latest posts. So my problem is that my homepage is being paginated. I don't want that.
I want my homepage to act as a homepage. Lets say my homepage is **example.com** , and shows the latest 2 posts **example.com** / _page/2/_ it show the previous two. I've added that code in the top of the index.php but is just a redirection. I want the pagination just disabled for that specific loop. How can I achieve that?
Thank you
`<?php if ($paged > 1) { header('Location: /blog'); exit; } ?>` | Make use of the WordPress template hierarchy, by either having a `home.php` \- home page - or a `front-page.php` \- front page - to display the site home/front. Read the WordPress codex article Creating a Static Front Page for an insight on how to do it and some explanation about the differences. Do not use any pagination code - see the according section from the before mentioned article. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pagination, homepage, paginate links"
} |
Track tags in Google Analytics?
I'd like to track tags for our posts in GA. Is there a way to submit them and have them associated the same way they apply in Wordpress, so that you can see how a particular tag is doing?
For example, we would be able to see how all posts tagged "movies" and "Vin Diesel" are doing. This seems like it should be a common enough issue, but I didn't see a great solution in my searching.
Right now our best idea is to submit all the tags in one long string. Then to analyze we have to do a data extract and some manipulation. Is there a better way? | Take a look at custom variables for Google Analytics. In that case you would need to parse all used tags as one string (maybe separated by | for example), because it's better to use one variable name and each variable can take one value per pageview.
Another option would be using events, using a category (named tags for example), which you could repeat for all tags used on a page. I think that is the best solution, since you can fire the same event category multiple times in one pageview. And this way you can search and compare the values within GA easily. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "tags, google analytics"
} |
Migrate posts and photos from a blog to another
i have an old blog that was made by a guy.
Now i'm trying to learn wordpress so i made my own blog, with different theme and template.
I asked my friend to send me a copy of the database of the old blog, so i'll be able to have all my old posts on my new blog.
How can i do that?
I uploaded the database but when i do that it asks me the Admin account of the old blog... but i don't have them and my friend is abroad and he can't help me as of now.
Where do i do wrong? did he do something wrong when he saved the db? Should i change lines in the db file so i will remove the old password? | I'm assuming you have an sql file that you're uploading?
If so, open that file in a text editor such as Notepad. Search for 'user_login', and somewhere nearby that you should see something similar to `'INSERT INTO wp_users (ID,user_login'` etc. On the next line after this, you should see something like `(1, 'admin', 'password'` where 'admin' is the admin username, and 'password' is the hashed password.
You can't login directly with that hashed password. But what you can do here is change the e-mail address listed on that line to one that you can access, then save the file.
Upload it into your Wordpress install again, and this time follow the forgot password link. Enter that e-mail address you put in, and you should be able to reset the password!
Alternatively, you can use an MD5 generator like < enter a new password there and copy the hash to replace the existing password in the SQL file. That will also let you log in with the new password.
Hope that helps! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "migration"
} |
Set order acs and no paging for archive page
My code theme archive.php is
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', 'test' get_post_format() );
?>
<?php endwhile; ?>
<?php semplicemente_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
So i want to change order from desc to acs , orderby date and post per page is 100.
I found it.
$args = ( array(
'order' => 'ASC',
'orderby' => 'date',
'posts_per_page' => '100',) );
So i put $args to get_post_format(), the_post() put nothing happen?
Any idea?
Thank for you help | So thanks for your help. Now i pay more attention to functions.php so my old code have effectively.
/* Change page order */
add_filter( 'pre_get_posts' , 'my_change_order' );
function my_change_order( $query ) {
// Check if the query is for an archive
if($query->is_archive)
// Query was for archive, then set order
$query->set( 'order' , 'asc' );
// Return the query (else there's no more query, oops!)
return $query;
}
// Code no paging//
function no_nopaging($query) {
if (is_date()) {
$query->set('nopaging', 1);
}
}
add_action('parse_query', 'no_nopaging'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, archives"
} |
Changing some of the language within the revision viewer admin page revision.php
I have a custom post type, to which the term "post" is irelevent. I had managed via various hooks to change all references of "post" to something else in the main post editing pages. I suddenly enabled revision support in my custom post and then realised that some text on the revision page needs updating.
I haven't been able to find a quick and fairly easy way to do this though. It's really small things like the link top left of the page that currently states "Return to post editor".
Any ideas anyone? | I resolved this in the end with some careful jQuery code that is run via a new JS file that is only loaded via the admin system pages.
To give an example of the jQuery code...
jQuery('.wrap a').each(function() {
if ( getCurentFileName()=="revision.php" ){
var text = jQuery(this).text();
jQuery(this).text(text.replace('← Return to post editor', '← the new replacement text'));
}
});
function getCurentFileName(){
var pagePathName= window.location.pathname;
return pagePathName.substring(pagePathName.lastIndexOf("/") + 1);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, language"
} |
Disable revision access for a specific user role
I want to disable revision access for a specific user role.
I saw the code posted here: Enable/disable post revisions programmatically but am worried that even with a clause to check the current admin users role that this code would disable the revision access site wide, not just to that specific user in that specific moment.
Has anyone done this? | I resolved this in the end by removing access to the revisions meta box for certain user types...
if (get_current_user_role()=="custom_user_role"){
function my_remove_revisions() {
remove_meta_box('revisionsdiv', 'apartments', 'normal');
}
add_action( 'admin_menu', 'my_remove_revisions' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "revisions"
} |
How to display post in custom file not in archive file?
I create file content-expertises.php and display my category list. Now, When I click one my category name, it is redirect in category.php file not my custom created file like category-expertise.php.
My current path is:
When I click my category name it is redirect in:
But, not redirect in my custom created (file is clone of archive file):
| Is the file named content-expertises.php or category-expertises.php?
WP will use the first template file it finds in your theme directory from the following list:
category-slug.php
category-ID.php
category.php
archive.php
index.php
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, redirect, archives, wp redirect"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.