qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
251,877 | <p>Thanks for any help.</p>
<p>I am in a custom post (not an archive) with a taxonomy.
And I'd like to display : </p>
<ul>
<li>some other custom posts</li>
<li>with this <b>current taxonomy</b></li>
</ul>
<p>Doesn't seems so hard but for me it does...
I didn't find the right way to use the term of my tax in the query...</p>
<p>Here is (one of) my try :</p>
<pre>
$terms = wp_get_post_terms( $post->ID, 'identite'); // to get my taxonomy
foreach ( $terms as $term ) {
echo "$term->slug"; // just for test - ok
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => $terms
)
),
);// end args
$query = new WP_Query( $args);
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Little pray, but doesn't work
}//end of while
}
</pre>
<p>I obtain this error message :
<em>Object of class WP_Term could not be converted to int in</em></p>
<p>Any idea to convert my object and make it readable ?
Thanks a lot</p>
<p><em>(edit : I try with the function wp_list_pluck but without success)</em></p>
| [
{
"answer_id": 251884,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 2,
"selected": true,
"text": "<p>Try this for <code>WP_Query</code></p>\n\n<pre><code>$args = array(\n'post_type' => 'example',\n... | 2017/01/09 | [
"https://wordpress.stackexchange.com/questions/251877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110465/"
] | Thanks for any help.
I am in a custom post (not an archive) with a taxonomy.
And I'd like to display :
* some other custom posts
* with this **current taxonomy**
Doesn't seems so hard but for me it does...
I didn't find the right way to use the term of my tax in the query...
Here is (one of) my try :
```
$terms = wp_get_post_terms( $post->ID, 'identite'); // to get my taxonomy
foreach ( $terms as $term ) {
echo "$term->slug"; // just for test - ok
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => $terms
)
),
);// end args
$query = new WP_Query( $args);
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Little pray, but doesn't work
}//end of while
}
```
I obtain this error message :
*Object of class WP\_Term could not be converted to int in*
Any idea to convert my object and make it readable ?
Thanks a lot
*(edit : I try with the function wp\_list\_pluck but without success)* | Try this for `WP_Query`
```
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => $term->term_id
)
),
);// end args
```
OR
```
$args = array(
'post_type' => 'example',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'identite',
'field' => 'ID',
'terms' => array($term->term_id)
)
),
);// end args
```
`$term` is an object and `tax_query` expects an array of id's.
See: <https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters> |
251,890 | <p>I've custom post "products" with standart categories and subcategories. Now I need to display a list of products on category page, that current category contains.</p>
<p>If category don't have subcategories I need to display this:</p>
<pre><code><ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
</code></pre>
<p>And if category contains sub categories display this:</p>
<pre><code><span class="subhead-title">Subcat 1</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
<span class="subhead-title">Subcat 2</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
</code></pre>
<p>How can I modyfy my <code>categories.php</code> to make my case done? Thanks in advance!</p>
| [
{
"answer_id": 251892,
"author": "Marc-Antoine Parent",
"author_id": 110578,
"author_profile": "https://wordpress.stackexchange.com/users/110578",
"pm_score": 0,
"selected": false,
"text": "<p>Once you have the primary category (the one that's loaded to the categories.php template), you ... | 2017/01/10 | [
"https://wordpress.stackexchange.com/questions/251890",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48584/"
] | I've custom post "products" with standart categories and subcategories. Now I need to display a list of products on category page, that current category contains.
If category don't have subcategories I need to display this:
```
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
```
And if category contains sub categories display this:
```
<span class="subhead-title">Subcat 1</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
<span class="subhead-title">Subcat 2</span>
<ul class="cat-arc-links">
<li><a href="#" class="product-link">Product 1</a></li>
<li><a href="#" class="product-link">Product 2</a></li>
<li><a href="#" class="product-link">Product 3</a></li>
......
</ul>
```
How can I modyfy my `categories.php` to make my case done? Thanks in advance! | Thanks to all! Here is my solution which worknig well
```
<?php
$cat = get_query_var('cat');
$categories = get_categories('parent='.$cat.'');
if(isset($categories) && !empty($categories)){
foreach ($categories as $category) { ?>
<span class="subhead-title"><?php echo $category->name; ?></span>
<?php $prods = new WP_query(); $prods->query('post_type=products&cat=' . $category->cat_ID . ''); ?>
<?php if($prods->have_posts()) { ?> <ul class="cat-arc-links"> <?php while ($prods->have_posts()) { $prods->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" class="product-link"><?php the_title(); ?></a></li>
<?php } ?> </ul> <?php } ?>
<?php }
}
else
{
global $query_string; // basic query parameters
query_posts( $query_string.'&post_type=products'); // basic query + self parameters
if( have_posts() ) { ?> <ul class="cat-arc-links"> <?php while( have_posts() ){ the_post(); ?>
<li><a href="<?php the_permalink(); ?>" class="product-link"><?php the_title(); ?></a></li>
<?php } /* end of while */ wp_reset_query(); ?>
</ul>
<div class="navigation">
<div class="next-posts"><?php next_posts_link(); ?></div>
<div class="prev-posts"><?php previous_posts_link(); ?></div>
</div>
<?php
}
else
echo "<h2>No entries.</h2>";
}
?>
``` |
251,898 | <p>In a plugin I have a payment form that needs to be submitted (via the action= attribute) to a .php file, also located in my plugin directly. After some research, it seems like the "wordpress way" to call up individual plugin files is to actually use custom queries on index.php instead. I've done so with the below code, and it's working, however the code in question simply needs to process the form and then redirect the user to a confirmation page, I don't need to display anything. Right now it seems like it's actually loading the index.php template, which seems like a waste.</p>
<p>Am I going about this correctly? If not, how should I do this instead?</p>
<pre><code>//Register our custom request hook
function tps_space_rental_query_vars($vars) {
$vars[] = 'tps-rent-space';
return $vars;
}
add_filter('query_vars', 'tps_space_rental_query_vars');
//This will allow us to process our payment form the wordpress way
function tps_payment_parse_request($wp) {
if (array_key_exists('tps-rent-space', $wp->query_vars)
&& $wp->query_vars['tps-rent-space'] == 'chargeform') {
// process the request, just testing for now
echo 'This request happened!';
}
}
add_action('parse_request', 'tps_payment_parse_request');
</code></pre>
| [
{
"answer_id": 251945,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 2,
"selected": true,
"text": "<p>the easiest way is using init action hook</p>\n\n<pre><code>add_action(\"init\", \"your_form_handler_actio... | 2017/01/10 | [
"https://wordpress.stackexchange.com/questions/251898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23492/"
] | In a plugin I have a payment form that needs to be submitted (via the action= attribute) to a .php file, also located in my plugin directly. After some research, it seems like the "wordpress way" to call up individual plugin files is to actually use custom queries on index.php instead. I've done so with the below code, and it's working, however the code in question simply needs to process the form and then redirect the user to a confirmation page, I don't need to display anything. Right now it seems like it's actually loading the index.php template, which seems like a waste.
Am I going about this correctly? If not, how should I do this instead?
```
//Register our custom request hook
function tps_space_rental_query_vars($vars) {
$vars[] = 'tps-rent-space';
return $vars;
}
add_filter('query_vars', 'tps_space_rental_query_vars');
//This will allow us to process our payment form the wordpress way
function tps_payment_parse_request($wp) {
if (array_key_exists('tps-rent-space', $wp->query_vars)
&& $wp->query_vars['tps-rent-space'] == 'chargeform') {
// process the request, just testing for now
echo 'This request happened!';
}
}
add_action('parse_request', 'tps_payment_parse_request');
``` | the easiest way is using init action hook
```
add_action("init", "your_form_handler_action");
function your_form_handler_action(){
if( isset( $_REQUEST["action"] ) && $_REQUEST["action"] == "your_action_name" ) {
echo "Response!!!";
}
}
``` |
251,908 | <p>So I've been working in Wordpress lately with Ajax and I managed to get some stock data into my site from my database. However, I am now trying to use Ajax to load Wordpress posts into my left sidebar, which requires the use of Wordpress functions and it seems as if I am not doing this properly.get_option() shows NULL on this.</p>
<p>JS</p>
<pre><code> url:"<?php echo get_template_directory_uri(); ?>/sendContactForm.php",//request URL
type:"POST",//Request type GET/POST
data: $(_this).serialize()
</code></pre>
<p>PHP(sendContactForm.php)</p>
<pre><code>$result = new stdClass();
$from = $_REQUEST['email'];
$message = $_REQUEST['message'];
$sender = $_REQUEST['email'];
$result->message = $message;
$result->subject = $_REQUEST['name'] . " send you a message";
$result->to = "get_option('admin_email');
$result->to = "get_option('admin_email'); showing NULL
</code></pre>
| [
{
"answer_id": 251911,
"author": "magicroundabout",
"author_id": 10046,
"author_profile": "https://wordpress.stackexchange.com/users/10046",
"pm_score": 3,
"selected": true,
"text": "<p>I confess that I'm slightly confused by how your sending email function loads posts into your sidebar.... | 2017/01/10 | [
"https://wordpress.stackexchange.com/questions/251908",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101257/"
] | So I've been working in Wordpress lately with Ajax and I managed to get some stock data into my site from my database. However, I am now trying to use Ajax to load Wordpress posts into my left sidebar, which requires the use of Wordpress functions and it seems as if I am not doing this properly.get\_option() shows NULL on this.
JS
```
url:"<?php echo get_template_directory_uri(); ?>/sendContactForm.php",//request URL
type:"POST",//Request type GET/POST
data: $(_this).serialize()
```
PHP(sendContactForm.php)
```
$result = new stdClass();
$from = $_REQUEST['email'];
$message = $_REQUEST['message'];
$sender = $_REQUEST['email'];
$result->message = $message;
$result->subject = $_REQUEST['name'] . " send you a message";
$result->to = "get_option('admin_email');
$result->to = "get_option('admin_email'); showing NULL
``` | I confess that I'm slightly confused by how your sending email function loads posts into your sidebar...the code does not seem to be doing the thing that you described.
Are you loading WordPress in sendContactForm.php? Is what you've shown here the only code in sendContactForm.php?
`get_option()` is a WordPress function, so you need to load WordPress to do this. This is usually done by putting something at the top of your php file like:
`require('../../../wp-load.php');`
But that's a bit hacky.
The proper way to do AJAX in WordPress is to send your POST request to `/wp-admin/admin-ajax.php` with an parameter like `action=sendContactForm` and then create an action hook like this:
```
add_action('wp_ajax_sendContactForm', 'my_email_function');
add_action('wp_ajax_nopriv_sendContactForm', 'my_email_function');
function my_email_function() {
// process request here
wp_die();
}
```
Read more about this at: <https://codex.wordpress.org/AJAX_in_Plugins> |
252,004 | <p>I'm attempting to change the "← Back to sitename" text on the wp-login.php page using gettext but not having much luck.</p>
<p>No matter what I try it doesn't seem to want to work, although I've had success changing the "Lost your password?" text using the same method.</p>
<p>Here is my latest snippet</p>
<pre><code>function custom_login_text ( $text ) {
if (in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) )) {
if ($text == '&larr; Back to %s'){$text = 'Test';}
return $text;
}
}
add_filter( 'gettext', 'custom_login_text' );
</code></pre>
<p>I've also tried directly using <code>← Back to Site Name</code> but that didn't work either. Am I missing something?</p>
<p>Any tips would be appreciated.</p>
| [
{
"answer_id": 251952,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": 1,
"selected": false,
"text": "<p>It's usually a permissions error. We used to have these issues on our older servers. As a general rule for ... | 2017/01/10 | [
"https://wordpress.stackexchange.com/questions/252004",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12238/"
] | I'm attempting to change the "← Back to sitename" text on the wp-login.php page using gettext but not having much luck.
No matter what I try it doesn't seem to want to work, although I've had success changing the "Lost your password?" text using the same method.
Here is my latest snippet
```
function custom_login_text ( $text ) {
if (in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) )) {
if ($text == '← Back to %s'){$text = 'Test';}
return $text;
}
}
add_filter( 'gettext', 'custom_login_text' );
```
I've also tried directly using `← Back to Site Name` but that didn't work either. Am I missing something?
Any tips would be appreciated. | It's usually a permissions error. We used to have these issues on our older servers. As a general rule for file permissions, you should never allow a folder to be "777" (Read/Write/Execute), but the uploads folder on this server, unfortunately, might need it. If you don't know what I'm talking about, please take a read through of [Wordpress' guide to Changing File Permissions](https://codex.wordpress.org/Changing_File_Permissions). |
252,027 | <p>I want to sanitize the title of a specific custom post type. I've managed to create a filter which sanitizes the titles. How ever It affects rest of the post types as well. After a lot of search I've managed to write an action which enables me to execute functions on specific pages on the admin panel. But I'm incapable of firing filters in actions.</p>
<p>So any help is appreciated. </p>
<pre><code>function check_cpt( $hook_suffix ){
$cpt = 'custom_post_type';
if( in_array($hook_suffix, array('post-new.php', 'post.php') ) ){
$screen = get_current_screen();
if( is_object( $screen ) && $cpt == $screen->post_type ){
echo'I'm only visible on custom post type';
die;
//add_filter( 'sanitize_title', 'url_sanitizer', 10, 3 );
//above filter doesnt work
}
}
}
add_action( 'admin_enqueue_scripts', 'check_cpt');
</code></pre>
<p>The above action works just as I intended.How ever I cannot fire the filter.
This is the filter function</p>
<pre><code>function url_sanitizer( $title, $raw_title, $context) {
$new_title = $raw_title;
$new_title = str_replace( ' ', '_', $new_title );
$new_title = str_replace( '-', '_', $new_title );
return $new_title;
}
</code></pre>
| [
{
"answer_id": 252030,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 2,
"selected": true,
"text": "<p>you want to sanitize the title or the post_name (slug)?\n<br>\nif you want to filter post_name you can che... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252027",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48438/"
] | I want to sanitize the title of a specific custom post type. I've managed to create a filter which sanitizes the titles. How ever It affects rest of the post types as well. After a lot of search I've managed to write an action which enables me to execute functions on specific pages on the admin panel. But I'm incapable of firing filters in actions.
So any help is appreciated.
```
function check_cpt( $hook_suffix ){
$cpt = 'custom_post_type';
if( in_array($hook_suffix, array('post-new.php', 'post.php') ) ){
$screen = get_current_screen();
if( is_object( $screen ) && $cpt == $screen->post_type ){
echo'I'm only visible on custom post type';
die;
//add_filter( 'sanitize_title', 'url_sanitizer', 10, 3 );
//above filter doesnt work
}
}
}
add_action( 'admin_enqueue_scripts', 'check_cpt');
```
The above action works just as I intended.How ever I cannot fire the filter.
This is the filter function
```
function url_sanitizer( $title, $raw_title, $context) {
$new_title = $raw_title;
$new_title = str_replace( ' ', '_', $new_title );
$new_title = str_replace( '-', '_', $new_title );
return $new_title;
}
``` | you want to sanitize the title or the post\_name (slug)?
if you want to filter post\_name you can check `wp_unique_post_slug` filter or you can use the `wp_insert_post_data` filter to filter all post data before insert or update in db.
```
add_filter( "wp_unique_post_slug", "url_sanitizer", 10, 4 );
function url_sanitizer( $slug, $post_ID, $post_status, $post_type ) {
// get original title by $post_ID if needed eg. get_the_title($post_ID)
if( $post_type == "your_cpt" ) {
$slug= str_replace( ' ', '_', $slug);
$slug= str_replace( '-', '_', $slug);
}
return $slug;
}
```
Reference:
`wp_unique_post_slug` documented in [wp-includes/post.php Line No. 3790](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L3790)
`wp_insert_post_data` <https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data> |
252,035 | <p>I am trying to make the page have 3 posts in each row, and then after 3 columns (12 posts) show the ajax load more button. Right now only one post is showing up. I don't know how to make it correctly loop through everything. Can anyone provide help? Thanks in advance.</p>
<pre class="lang-html prettyprint-override"><code><?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( [
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1)
] );
if ( $the_query->have_posts() ) { ?>
<div id="ajax">
<article class="post">
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
</div>
<?php if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
}
elseif (!get_query_var('paged') || get_query_var('paged') == '1') {
echo '<p>Sorry, no posts matched your criteria.</p>';
}
wp_reset_postdata();
get_footer();
</code></pre>
<p>UPDATED</p>
<pre class="lang-html prettyprint-override"><code><?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( array(
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1),
'cat' => 10,
));
if ( $the_query->have_posts() ) {
// display #ajax wrapper only if we have posts
echo '<div id="ajax">';
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<article <?php post_class(); ?>>
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
<?php }//end while
echo '</div>'; // close the #ajax wrapper after the post list
if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
} else { // if there are no posts
echo '<p>Sorry, no posts matched your criteria.</p>';
}//end if
get_footer();
?>
</code></pre>
| [
{
"answer_id": 252036,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 0,
"selected": false,
"text": "<p>Your code doesn't have <code>while</code> loop</p>\n\n<pre><code>if ( $the_query->have_posts() ... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101743/"
] | I am trying to make the page have 3 posts in each row, and then after 3 columns (12 posts) show the ajax load more button. Right now only one post is showing up. I don't know how to make it correctly loop through everything. Can anyone provide help? Thanks in advance.
```html
<?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( [
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1)
] );
if ( $the_query->have_posts() ) { ?>
<div id="ajax">
<article class="post">
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
</div>
<?php if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
}
elseif (!get_query_var('paged') || get_query_var('paged') == '1') {
echo '<p>Sorry, no posts matched your criteria.</p>';
}
wp_reset_postdata();
get_footer();
```
UPDATED
```html
<?php
get_header();
get_template_part ('inc/carousel-food');
$the_query = new WP_Query( array(
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1),
'cat' => 10,
));
if ( $the_query->have_posts() ) {
// display #ajax wrapper only if we have posts
echo '<div id="ajax">';
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<article <?php post_class(); ?>>
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
<?php }//end while
echo '</div>'; // close the #ajax wrapper after the post list
if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
} else { // if there are no posts
echo '<p>Sorry, no posts matched your criteria.</p>';
}//end if
get_footer();
?>
``` | I just tested the following example code:
```
<?php
$the_query = new WP_Query( array(
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1)
));
if ( $the_query->have_posts() ) {
// display #ajax wrapper only if we have posts
echo '<div id="ajax">';
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<article <?php post_class(); ?>>
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
<?php }//end while
echo '</div>'; // close the #ajax wrapper after the post list
if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
} else { // if there are no posts
echo '<p>Sorry, no posts matched your criteria.</p>';
}//end if
?>
```
The `<div id="ajax">` should wrap around the whole post-list and not every single post, correct? Than this container should be outside the while loop!
Also, when you not specify any post-type in the WP\_Query, it defaults to "any" type. So make sure you want this!
>
> 'any' - retrieves any type except revisions and types with 'exclude\_from\_search' set to true.
>
>
>
In the `<article>` tag you should also use `<?php post_class(); ?>` instead of `class="post"` to get some more and helpful classes automaticly. (including current post-type, status and category)
**Update:**
>
> I've pasted the updated code above in my answer. It works at showing
> the posts. However it only showed one post in a row, so I added 2 more
> col-md-4. But now it just repeats the same post 3 times. How would I
> fix this? Also the ajax button will not appear.
>
>
>
OK so, first ... the loop has nothing to do **how** you will show the posts on the frontend.(in a grid or just below each other) I can see you tried to add 3 `<article>` elements in the `while` loop.
***This is wrong***, you just define the template of 1 `<article>` here, and all following will use the same.
You use CSS to define how the articles will display on the frontend. So for example use a % width on the article elements to display 3 in a row.
(100% / 3)
*Maybe* you can also use existing CSS classes. In your code I see `<div class="col-md-4">`, so this seems to already be a class of a grid/column system. So maybe look in the docs of the theme which you are using.
If that is already a class to display 3 cols in a row, maybe some CSS is overriding the width.
Yeah, you just need 1 article element, and than style with CSS. |
252,054 | <p><em>(Queries are definitively an infinite source of misunderstanding...)</em></p>
<p>I try to display two types of informations in a tax archive (<code>taxonomy-artiste.php</code>) : </p>
<ol>
<li>The content of a page from a custom post (bio)</li>
<li>And after, a list of post from another custom post (works)</li>
</ol>
<p>If I understood well, it could be interesting to use pre_get_post to change the main query.
So, I set that in my <code>function.php</code>.</p>
<pre>
//Include all my CPT but the bio
function lm_exclude_bio( $query ) {
if( is_tax('artiste') && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'cpt#1', 'cpt#2'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'lm_exclude_bio' );
</pre>
<p>Ok, it works.</p>
<p>But, when I add a new query in this archive, it doesn't display the post I excepted...</p>
<pre>
$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );
// My second query for CPT 'bio'
$bio_query = new WP_Query( $args );
// The Loop
if ( $bio_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$bio_query->the_post();
// please, my custom post 'bio' !...
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
?>
</pre>
<p>Is it impossible( stupid ?) to set two queries with opposite arguments ?
Thanks for any help !</p>
| [
{
"answer_id": 252057,
"author": "David Navia",
"author_id": 92828,
"author_profile": "https://wordpress.stackexchange.com/users/92828",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, first of all I found a misleading in your code, check the <code>while</code> part I ammended:</p>\n\n... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252054",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110465/"
] | *(Queries are definitively an infinite source of misunderstanding...)*
I try to display two types of informations in a tax archive (`taxonomy-artiste.php`) :
1. The content of a page from a custom post (bio)
2. And after, a list of post from another custom post (works)
If I understood well, it could be interesting to use pre\_get\_post to change the main query.
So, I set that in my `function.php`.
```
//Include all my CPT but the bio
function lm_exclude_bio( $query ) {
if( is_tax('artiste') && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'cpt#1', 'cpt#2'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'lm_exclude_bio' );
```
Ok, it works.
But, when I add a new query in this archive, it doesn't display the post I excepted...
```
$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );
// My second query for CPT 'bio'
$bio_query = new WP_Query( $args );
// The Loop
if ( $bio_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$bio_query->the_post();
// please, my custom post 'bio' !...
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
?>
```
Is it impossible( stupid ?) to set two queries with opposite arguments ?
Thanks for any help ! | You've added the filter `lm_exclude_bio` to `pre_get_posts`. So when you need to run another query you can remove the filter to get normal query. You can remove the filter like below-
```
// Here we're removing the filter first. Then we are running the query.
remove_filter( 'pre_get_posts', 'lm_exclude_bio' );
$args = array( 'post_type' => 'bio', 'posts_per_page' => 1 );
// My second query for CPT 'bio'
$bio_query = new WP_Query( $args );
// The Loop
if ( $bio_query->have_posts() ) {
while ( $bio_query->have_posts() ) {
$bio_query->the_post();
// please, my custom post 'bio' !...
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
?>
```
Also in `while ( $the_query->have_posts() )` you got a error on `$the_query`. It would be `$bio_query`. I've fixed the error in my above code.
Hope it helps. |
252,071 | <p>I am attempting to import a site using XML generated by WordPress.com</p>
<p>All the posts and media seem to import, but the comments fail with errors</p>
<pre><code>Failed to import “Sarah Toon - 2015-10-10 08:29:30”: Invalid post type feedback
Failed to import “Kylie - 2015-10-10 08:34:50”: Invalid post type feedback
Failed to import “Sophie Ward - 2015-10-10 08:36:22”: Invalid post type feedback
</code></pre>
<p>Reading other posts, here on WordPress.SE none of them have an accepted answer. The closest I could find is <a href="https://wordpress.stackexchange.com/questions/49531/custom-post-types-not-imported-properly">Custom post types not imported properly</a> but that is about posts, not comments.</p>
<p>Can someone get me started on solving this please?</p>
| [
{
"answer_id": 252078,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>The issue is you're trying to import posts with a post type of <code>feedback</code>, but there is no such ... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25717/"
] | I am attempting to import a site using XML generated by WordPress.com
All the posts and media seem to import, but the comments fail with errors
```
Failed to import “Sarah Toon - 2015-10-10 08:29:30”: Invalid post type feedback
Failed to import “Kylie - 2015-10-10 08:34:50”: Invalid post type feedback
Failed to import “Sophie Ward - 2015-10-10 08:36:22”: Invalid post type feedback
```
Reading other posts, here on WordPress.SE none of them have an accepted answer. The closest I could find is [Custom post types not imported properly](https://wordpress.stackexchange.com/questions/49531/custom-post-types-not-imported-properly) but that is about posts, not comments.
Can someone get me started on solving this please? | The issue is you're trying to import posts with a post type of `feedback`, but there is no such post type registered on your install of WordPress.
Quick-and-easy fix is to register one:
```
add_action( 'init', function () {
register_post_type( 'feedback', [
'public' => true,
'labels' => [
'singular_name' => 'Feedback',
'name' => 'Feedback',
]
]);
});
```
Place it in your theme's `functions.php`, or in a MU plugin (eg. `wp-content/mu-plugins/feedback.php`). |
252,073 | <p>Hi Guys i found this code snippet on here: </p>
<pre><code>add_action( 'set_user_role', function( $user_id, $role, $old_roles )
{
// Your code ...
}, 10, 3 );
</code></pre>
<p>Source: <a href="https://wordpress.stackexchange.com/questions/194324/execute-a-function-when-admin-changes-the-user-role">Execute a function when admin changes the user role</a></p>
<p>And wanted to modify it it so that it could set the user roles in the following way: </p>
<p>1 user has roles "level0" and "customer" -> roles "level1" and "vendor"</p>
<p>2 user has roles "level1" and "vendor" -> roles "level0" and "customer"</p>
<p>In case the admin is changing the role "level0" to "level1" the code should update the second role from "customer" to "vendor" and vice versa.</p>
<p>i tried the following code but it is not working:</p>
<pre><code>add_action( 'set_user_role', 'rb_update_user_role',10,3);
function rb_update_user_role(){
$user_id = get_current_user_id();
$user = new WP_User ($user_id);
if (current_user_is('s2member_level0') && current_user_is('vendor')){
$user->remove_role('vendor');
$user->add_role('customer');
}
if(current_user_is('s2member_level1') && current_user_is ('customer')){
$user->remove_role('customer');
$user->add_role('vendor');
}
}
</code></pre>
<p>Has anyone suggestions or code snippets that could help me figure this out? Or do i need another approch on this?</p>
<p>EDIT: </p>
<p>I add the second role like this when the user is activated </p>
<pre><code>add_action( 'bp_core_activated_user', 'add_secondary_role_new', 10, 1 );
function add_secondary_role_new( $user_id ) {
global $members_template;
$user = get_user_by('id', $user_id);
if (user_can($members_template->member->id,'s2member_level1')){
$user->add_role('vendor');
}
else{
$user->add_role('customer');
}
</code></pre>
<p>}</p>
| [
{
"answer_id": 252078,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>The issue is you're trying to import posts with a post type of <code>feedback</code>, but there is no such ... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252073",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102810/"
] | Hi Guys i found this code snippet on here:
```
add_action( 'set_user_role', function( $user_id, $role, $old_roles )
{
// Your code ...
}, 10, 3 );
```
Source: [Execute a function when admin changes the user role](https://wordpress.stackexchange.com/questions/194324/execute-a-function-when-admin-changes-the-user-role)
And wanted to modify it it so that it could set the user roles in the following way:
1 user has roles "level0" and "customer" -> roles "level1" and "vendor"
2 user has roles "level1" and "vendor" -> roles "level0" and "customer"
In case the admin is changing the role "level0" to "level1" the code should update the second role from "customer" to "vendor" and vice versa.
i tried the following code but it is not working:
```
add_action( 'set_user_role', 'rb_update_user_role',10,3);
function rb_update_user_role(){
$user_id = get_current_user_id();
$user = new WP_User ($user_id);
if (current_user_is('s2member_level0') && current_user_is('vendor')){
$user->remove_role('vendor');
$user->add_role('customer');
}
if(current_user_is('s2member_level1') && current_user_is ('customer')){
$user->remove_role('customer');
$user->add_role('vendor');
}
}
```
Has anyone suggestions or code snippets that could help me figure this out? Or do i need another approch on this?
EDIT:
I add the second role like this when the user is activated
```
add_action( 'bp_core_activated_user', 'add_secondary_role_new', 10, 1 );
function add_secondary_role_new( $user_id ) {
global $members_template;
$user = get_user_by('id', $user_id);
if (user_can($members_template->member->id,'s2member_level1')){
$user->add_role('vendor');
}
else{
$user->add_role('customer');
}
```
} | The issue is you're trying to import posts with a post type of `feedback`, but there is no such post type registered on your install of WordPress.
Quick-and-easy fix is to register one:
```
add_action( 'init', function () {
register_post_type( 'feedback', [
'public' => true,
'labels' => [
'singular_name' => 'Feedback',
'name' => 'Feedback',
]
]);
});
```
Place it in your theme's `functions.php`, or in a MU plugin (eg. `wp-content/mu-plugins/feedback.php`). |
252,079 | <p>I am using a Genesis theme (digital-pro), and inside of the front-page.php file (companion to functions.php) I am noticing that js files are enqueued in two different ways.</p>
<p>Example 1: </p>
<pre><code>wp_enqueue_script( 'localScroll', get_stylesheet_directory_uri() . '/js/jquery.localScroll.min.js', array( 'scrollTo' ), '1.2.8b', true );
</code></pre>
<p>Example 2: </p>
<pre><code>wp_enqueue_script( 'digital-backstretch-set', get_bloginfo('stylesheet_directory').'/js/backstretch-set.js' , array( 'jquery', 'digital-backstretch' ), '1.0.0' );
</code></pre>
<p>In the first example, <code>get_stylesheet_directory_uri()</code> is used before concatenating the js file path, and in the second example <code>get_bloginfo('stylesheet_directory')</code> is used instead. </p>
<p>Does anyone have any insight into why this might be? Is it better to use one method over the other? Or in different circumstances?</p>
<p>Thanks! </p>
| [
{
"answer_id": 252083,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>Starting from WordPress 4.7, I would use <a href=\"https://developer.wordpress.org/reference/functions/get_th... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252079",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110604/"
] | I am using a Genesis theme (digital-pro), and inside of the front-page.php file (companion to functions.php) I am noticing that js files are enqueued in two different ways.
Example 1:
```
wp_enqueue_script( 'localScroll', get_stylesheet_directory_uri() . '/js/jquery.localScroll.min.js', array( 'scrollTo' ), '1.2.8b', true );
```
Example 2:
```
wp_enqueue_script( 'digital-backstretch-set', get_bloginfo('stylesheet_directory').'/js/backstretch-set.js' , array( 'jquery', 'digital-backstretch' ), '1.0.0' );
```
In the first example, `get_stylesheet_directory_uri()` is used before concatenating the js file path, and in the second example `get_bloginfo('stylesheet_directory')` is used instead.
Does anyone have any insight into why this might be? Is it better to use one method over the other? Or in different circumstances?
Thanks! | Starting from WordPress 4.7, I would use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/), so any child theme can override the file easily: if the file exists in the child theme, `get_theme_file_uri()` returns the URI to that file, otherwise returns the file in the parent theme:
```
wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );
```
If you want to *hard* link to a file in the parent theme not allowing it to be overriden by a child theme, use [`get_parent_theme_file()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
But responding specifically to your question, both methods do the same; in fact, `get_bloginfo( 'stylesheet_directory' )` is a wrapper for `get_stylesheet_directory_uri()` as you can see in the [source code](https://developer.wordpress.org/reference/functions/get_bloginfo/#source):
```
case 'stylesheet_directory':
$output = get_stylesheet_directory_uri();
break;
```
But I would avoid `get_bloginfo()` if a specific getter function exists; it may be more consistent in long way.
`get_stylesheet_directory_uri()` and `get_template_directory_uri()` still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template **directory**, not a URI to a **file**.
For example, imaging we have a file located in `assets/js/script.js` whithin the theme folder; then we can use all of this options:
1. `get_styleseet_directory_uri() . '/assets/js/script.js';`
2. `get_template_directory_uri() . '/assets/js/script.js';`
3. `get_theme_file_uri( 'assets/js/script.js' );`
In a theme with no childs, all three options will output the **same URI**; but if you develop a child theme:
1. The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.
2. The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).
3. With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.
Internally, `get_theme_file_uri()`first checks if the file exists in the stylesheet directory, if it exists it returns `get_styleseet_directory_uri() . $file;`. If the file doesn't exist in the child theme, then it returns `get_template_directory_uri() . $file;`. It is like one level up over the other functions.
Along with `get_theme_file_uri()`, `get_theme_file_path()` was introduced to get the path to the file instead of the URI; `get_parent_theme_file_uri()` and `get_parent_theme_file_path()` are also available but they will always use the parent file files, no matter if a child theme is active. |
252,085 | <p>Hi I am using thevoux theme for my website as i need to add pagination links like "Older Posts and Newer Posts" to home page.Here is an example screen shot how it should be.
<a href="https://i.stack.imgur.com/4rWAj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4rWAj.jpg" alt="enter image description here"></a></p>
<p>Actually right now i am getting these links in menus in the same way i need to display them in home page as well.</p>
<pre><code><?php get_header(); ?>
<?php
$blog_featured = ot_get_option('blog_featured');
?>
<?php if ($blog_featured) { ?>
<div class="row header_content">
<div class="small-12 columns">
<?php
$args = array(
'p' => $blog_featured,
'post_type' => 'any'
);
$featured_post = new WP_Query($args);
?>
<?php if ($featured_post->have_posts()) : while ($featured_post->have_posts()) : $featured_post->the_post(); ?>
<?php get_template_part( 'inc/loop/blog-featured' ); ?>
<?php endwhile; else : endif; ?>
</div>
</div>
<?php } ?>
<div class="row">
<section class="blog-section small-12 medium-8 columns">
<div class="row" data-equal=">.columns">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part( 'inc/loop/blog-list' ); ?>
<?php endwhile; else : ?>
<?php get_template_part( 'inc/loop/notfound' ); ?>
<?php endif; ?>
</div>
<?php if ( get_next_posts_link() || get_previous_posts_link()) { ?>
<div class="blog_nav">
<?php if ( get_next_posts_link() ) : ?>
<a href="<?php echo next_posts(); ?>" class="next"><i class="fa fa-angle-left"></i> <?php _e( 'Older Posts', 'thevoux' ); ?></a>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<a href="<?php echo previous_posts(); ?>" class="prev"><?php _e( 'Newer Posts', 'thevoux' ); ?> <i class="fa fa-angle-right"></i></a>
<?php endif; ?>
</div>
<?php } ?>
</section>
<?php get_sidebar(); ?>
</div>
</code></pre>
| [
{
"answer_id": 252083,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>Starting from WordPress 4.7, I would use <a href=\"https://developer.wordpress.org/reference/functions/get_th... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252085",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110685/"
] | Hi I am using thevoux theme for my website as i need to add pagination links like "Older Posts and Newer Posts" to home page.Here is an example screen shot how it should be.
[](https://i.stack.imgur.com/4rWAj.jpg)
Actually right now i am getting these links in menus in the same way i need to display them in home page as well.
```
<?php get_header(); ?>
<?php
$blog_featured = ot_get_option('blog_featured');
?>
<?php if ($blog_featured) { ?>
<div class="row header_content">
<div class="small-12 columns">
<?php
$args = array(
'p' => $blog_featured,
'post_type' => 'any'
);
$featured_post = new WP_Query($args);
?>
<?php if ($featured_post->have_posts()) : while ($featured_post->have_posts()) : $featured_post->the_post(); ?>
<?php get_template_part( 'inc/loop/blog-featured' ); ?>
<?php endwhile; else : endif; ?>
</div>
</div>
<?php } ?>
<div class="row">
<section class="blog-section small-12 medium-8 columns">
<div class="row" data-equal=">.columns">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part( 'inc/loop/blog-list' ); ?>
<?php endwhile; else : ?>
<?php get_template_part( 'inc/loop/notfound' ); ?>
<?php endif; ?>
</div>
<?php if ( get_next_posts_link() || get_previous_posts_link()) { ?>
<div class="blog_nav">
<?php if ( get_next_posts_link() ) : ?>
<a href="<?php echo next_posts(); ?>" class="next"><i class="fa fa-angle-left"></i> <?php _e( 'Older Posts', 'thevoux' ); ?></a>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<a href="<?php echo previous_posts(); ?>" class="prev"><?php _e( 'Newer Posts', 'thevoux' ); ?> <i class="fa fa-angle-right"></i></a>
<?php endif; ?>
</div>
<?php } ?>
</section>
<?php get_sidebar(); ?>
</div>
``` | Starting from WordPress 4.7, I would use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/), so any child theme can override the file easily: if the file exists in the child theme, `get_theme_file_uri()` returns the URI to that file, otherwise returns the file in the parent theme:
```
wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );
```
If you want to *hard* link to a file in the parent theme not allowing it to be overriden by a child theme, use [`get_parent_theme_file()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
But responding specifically to your question, both methods do the same; in fact, `get_bloginfo( 'stylesheet_directory' )` is a wrapper for `get_stylesheet_directory_uri()` as you can see in the [source code](https://developer.wordpress.org/reference/functions/get_bloginfo/#source):
```
case 'stylesheet_directory':
$output = get_stylesheet_directory_uri();
break;
```
But I would avoid `get_bloginfo()` if a specific getter function exists; it may be more consistent in long way.
`get_stylesheet_directory_uri()` and `get_template_directory_uri()` still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template **directory**, not a URI to a **file**.
For example, imaging we have a file located in `assets/js/script.js` whithin the theme folder; then we can use all of this options:
1. `get_styleseet_directory_uri() . '/assets/js/script.js';`
2. `get_template_directory_uri() . '/assets/js/script.js';`
3. `get_theme_file_uri( 'assets/js/script.js' );`
In a theme with no childs, all three options will output the **same URI**; but if you develop a child theme:
1. The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.
2. The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).
3. With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.
Internally, `get_theme_file_uri()`first checks if the file exists in the stylesheet directory, if it exists it returns `get_styleseet_directory_uri() . $file;`. If the file doesn't exist in the child theme, then it returns `get_template_directory_uri() . $file;`. It is like one level up over the other functions.
Along with `get_theme_file_uri()`, `get_theme_file_path()` was introduced to get the path to the file instead of the URI; `get_parent_theme_file_uri()` and `get_parent_theme_file_path()` are also available but they will always use the parent file files, no matter if a child theme is active. |
252,121 | <p>I want to resize images in uploads folder. What would be the best way to resize images on a live website?</p>
| [
{
"answer_id": 252083,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>Starting from WordPress 4.7, I would use <a href=\"https://developer.wordpress.org/reference/functions/get_th... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I want to resize images in uploads folder. What would be the best way to resize images on a live website? | Starting from WordPress 4.7, I would use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/), so any child theme can override the file easily: if the file exists in the child theme, `get_theme_file_uri()` returns the URI to that file, otherwise returns the file in the parent theme:
```
wp_enqueue_script( 'localScroll', get_theme_file_uri( 'js/jquery.localScroll.min.js' ), array( 'scrollTo' ), '1.2.8b', true );
```
If you want to *hard* link to a file in the parent theme not allowing it to be overriden by a child theme, use [`get_parent_theme_file()`](https://developer.wordpress.org/reference/functions/get_parent_theme_file_uri/).
But responding specifically to your question, both methods do the same; in fact, `get_bloginfo( 'stylesheet_directory' )` is a wrapper for `get_stylesheet_directory_uri()` as you can see in the [source code](https://developer.wordpress.org/reference/functions/get_bloginfo/#source):
```
case 'stylesheet_directory':
$output = get_stylesheet_directory_uri();
break;
```
But I would avoid `get_bloginfo()` if a specific getter function exists; it may be more consistent in long way.
`get_stylesheet_directory_uri()` and `get_template_directory_uri()` still exists, are valid and can be used but those functions should be used only when you need specifically the URI of the shtylesheet/template **directory**, not a URI to a **file**.
For example, imaging we have a file located in `assets/js/script.js` whithin the theme folder; then we can use all of this options:
1. `get_styleseet_directory_uri() . '/assets/js/script.js';`
2. `get_template_directory_uri() . '/assets/js/script.js';`
3. `get_theme_file_uri( 'assets/js/script.js' );`
In a theme with no childs, all three options will output the **same URI**; but if you develop a child theme:
1. The option 1 will link to a file in the child theme directory whitout checking if it exists. In this case, we are required to copy the file to the child theme, even if we don't need to modify it.
2. The option 2 will link to a file in the parent theme; no options to override it (well, it can be done using some filter hooks, but not in a direct way).
3. With the option 3 you can leave the file in the parent theme if you are not going to modify it; or you can move the file to the child theme if you need to override it. No extra code is needed. As easy as it is sound.
Internally, `get_theme_file_uri()`first checks if the file exists in the stylesheet directory, if it exists it returns `get_styleseet_directory_uri() . $file;`. If the file doesn't exist in the child theme, then it returns `get_template_directory_uri() . $file;`. It is like one level up over the other functions.
Along with `get_theme_file_uri()`, `get_theme_file_path()` was introduced to get the path to the file instead of the URI; `get_parent_theme_file_uri()` and `get_parent_theme_file_path()` are also available but they will always use the parent file files, no matter if a child theme is active. |
252,133 | <p>I am having trouble finding a good resource on using the $wpdb function.</p>
<p>I am trying to delete a row from a custom table named: eLearning_progress</p>
<pre><code>$removefromdb = $wpdb->query("DELETE FROM eLearning_progress WHERE ID = '$user_id' AND module_id = '$singlecomparearrays_remove'" );
</code></pre>
<p>The row I would like to delete has the ID of '$user_id' and the 'module_id' of '$singlecomparearrays_remove'.</p>
<p>I have also tried: </p>
<pre><code>$removefromdb = $wpdb->query( "DELETE FROM eLearning_progress WHERE ID = ($user_id) AND module_id = ($singlecomparearrays_remove)" );
</code></pre>
<p>and then:</p>
<pre><code>$removefromdb = $wpdb->query($wpdb->prepare("DELETE FROM eLearning_progress WHERE ID = %s AND module_id = %s", $user_id, $singlecomparearrays_remove));
</code></pre>
<p>Please try not to sigh too loudly at my attempts but I can't find a good guide on using the DELETE command with variables in there too.
Any help is much appreciated.</p>
<p>Regards,
Alex</p>
| [
{
"answer_id": 252222,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 6,
"selected": true,
"text": "<p>The best WP API solution for this goal is to use the <a href=\"https://developer.wordpress.org/reference/classes/w... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252133",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110723/"
] | I am having trouble finding a good resource on using the $wpdb function.
I am trying to delete a row from a custom table named: eLearning\_progress
```
$removefromdb = $wpdb->query("DELETE FROM eLearning_progress WHERE ID = '$user_id' AND module_id = '$singlecomparearrays_remove'" );
```
The row I would like to delete has the ID of '$user\_id' and the 'module\_id' of '$singlecomparearrays\_remove'.
I have also tried:
```
$removefromdb = $wpdb->query( "DELETE FROM eLearning_progress WHERE ID = ($user_id) AND module_id = ($singlecomparearrays_remove)" );
```
and then:
```
$removefromdb = $wpdb->query($wpdb->prepare("DELETE FROM eLearning_progress WHERE ID = %s AND module_id = %s", $user_id, $singlecomparearrays_remove));
```
Please try not to sigh too loudly at my attempts but I can't find a good guide on using the DELETE command with variables in there too.
Any help is much appreciated.
Regards,
Alex | The best WP API solution for this goal is to use the [`delete()`](https://developer.wordpress.org/reference/classes/wpdb/delete/) function to remove a row.
A small example, to delete the raw `ID` in the custom table `eLearning_progress`.
```php
$id = 0815;
$table = 'eLearning_progress';
$wpdb->delete( $table, array( 'id' => $id ) );
```
But I can't see which raw you will delete in your table `eLearning_progress`? Maybe you enhance the question to understand it much better. |
252,134 | <p>I'm trying to get value of hidden <code>textarea</code> created by <code>wp_editor()</code> or check if anything is typed it, but the problem is that the value is updated on submit, not dynamically. What I need is to validate with jQuery whether the field is filled in or not.</p>
<p>My field:</p>
<pre><code>$settings = array(
'editor_height' => 300,
'media_buttons' => false,
'teeny' => false,
'quicktags' => false
);
wp_editor( $post->post_content ,'my_content', $settings);
</code></pre>
<p>The only idea that I get is:</p>
<pre><code>var name = $('iframe#st_content_ifr').contents().find('#tinymce p').length;
</code></pre>
<p>and then count paragraphs, but this solution seems to me a bit silly. Is there any better way?</p>
| [
{
"answer_id": 252222,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 6,
"selected": true,
"text": "<p>The best WP API solution for this goal is to use the <a href=\"https://developer.wordpress.org/reference/classes/w... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105189/"
] | I'm trying to get value of hidden `textarea` created by `wp_editor()` or check if anything is typed it, but the problem is that the value is updated on submit, not dynamically. What I need is to validate with jQuery whether the field is filled in or not.
My field:
```
$settings = array(
'editor_height' => 300,
'media_buttons' => false,
'teeny' => false,
'quicktags' => false
);
wp_editor( $post->post_content ,'my_content', $settings);
```
The only idea that I get is:
```
var name = $('iframe#st_content_ifr').contents().find('#tinymce p').length;
```
and then count paragraphs, but this solution seems to me a bit silly. Is there any better way? | The best WP API solution for this goal is to use the [`delete()`](https://developer.wordpress.org/reference/classes/wpdb/delete/) function to remove a row.
A small example, to delete the raw `ID` in the custom table `eLearning_progress`.
```php
$id = 0815;
$table = 'eLearning_progress';
$wpdb->delete( $table, array( 'id' => $id ) );
```
But I can't see which raw you will delete in your table `eLearning_progress`? Maybe you enhance the question to understand it much better. |
252,135 | <p>After I moved Wordpress to a subfolder, I'm getting the following error at Chrome console:</p>
<pre><code>GET http://www.mydomain.comwp-includes/js/wp-embed.min.js?ver=4.5.4 net::ERR_NAME_NOT_RESOLVED
</code></pre>
<p>See? It's missing a "/" after the domain name.</p>
<p>What's the best approach to solve this? 301 redirects on htaccess seems very intrusive, is there any configuration I'm missing here?</p>
| [
{
"answer_id": 252136,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>I solved it by logging in into admin panel and saving site URL with a trailing slash at the end.</p>... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
] | After I moved Wordpress to a subfolder, I'm getting the following error at Chrome console:
```
GET http://www.mydomain.comwp-includes/js/wp-embed.min.js?ver=4.5.4 net::ERR_NAME_NOT_RESOLVED
```
See? It's missing a "/" after the domain name.
What's the best approach to solve this? 301 redirects on htaccess seems very intrusive, is there any configuration I'm missing here? | I solved it by logging in into admin panel and saving site URL with a trailing slash at the end. |
252,143 | <p>I have a snippet in my functions PHP file that allows me to upload SVG files. Since upgrading to the latest version of WP today, I can no longer upload svgs. I also tried a second code snippet from CSS tricks website and that doesn't work either. </p>
<p>Does anyone know a) what may have caused this with the last update and b) Does anyone know a work around.</p>
<p>Here is the code I normally use: </p>
<pre><code>function svg_mime_types( $mimes ) {
mimes['svg'] = 'image/svg+xml';
return $mimes;}
add_filter( 'upload_mimes', 'svg_mime_types' );
</code></pre>
<p>Many thanks</p>
<p>Paul.</p>
| [
{
"answer_id": 252162,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Seems like this might be related to this ticket <a href=\"https://core.trac.wordpress.org/ticket/39552\">... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I have a snippet in my functions PHP file that allows me to upload SVG files. Since upgrading to the latest version of WP today, I can no longer upload svgs. I also tried a second code snippet from CSS tricks website and that doesn't work either.
Does anyone know a) what may have caused this with the last update and b) Does anyone know a work around.
Here is the code I normally use:
```
function svg_mime_types( $mimes ) {
mimes['svg'] = 'image/svg+xml';
return $mimes;}
add_filter( 'upload_mimes', 'svg_mime_types' );
```
Many thanks
Paul. | In WordPress 4.7.1 [a change was introduced](https://core.trac.wordpress.org/changeset/39831) that checks for the real mime type of an uploaded file. This breaks uploading file types like SVG or DOCX. There already exist tickets for this issue in WordPress Core, where you can read more about this:
* Some Non-image files fail to upload after 4.7.1 (<https://core.trac.wordpress.org/ticket/39550>)
* SVG upload support broken in 4.7.1 (<https://core.trac.wordpress.org/ticket/39552>)
A **temporary** and recommended workaround (for the time until this issue is fixed) is the following plugin:
[**Disable Real MIME Check**](https://wordpress.org/plugins/disable-real-mime-check/)
If you don’t want to use that plugin, here’s the same functionality:
```
add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {
global $wp_version;
if ( '4.7.2' !== $wp_version ) {
return $data;
}
$filetype = wp_check_filetype( $filename, $mimes );
return [
'ext' => $filetype['ext'],
'type' => $filetype['type'],
'proper_filename' => $data['proper_filename']
];
}, 10, 4 );
```
Notice that this snipped has a version check included to disable the fix as soon as WordPress is updated.
**Edit**
The issue was initially set to be fixed in 4.7.2. But since [4.7.2 was an urgent security release](https://wordpress.org/news/2017/01/wordpress-4-7-2-security-release/), the fix didn’t make it into that version. It’s now supposed to be fixed in 4.7.3. |
252,150 | <p>I have a sidebar with all my post the page only displays one post at a time. I want to display the post that is clicked from the sidebar.</p>
<p>This is the single post display</p>
<pre><code><?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 1
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1 class=""><?php the_title(); ?></h1>
<div class="the-date"><p><br><?php the_time('F jS, Y') ?></p></div>
<div class=""><p><?php the_content(); ?></p></div>
<?php endwhile ?>
<?php endif ?>
</code></pre>
<p>This is the side bar displaying post i want to populate the post area </p>
<pre><code><?php
$recent_args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'offset' => 1
);
$the_recent = new WP_Query( $recent_args );
if ( $the_recent->have_posts() ) : ?>
<?php while ( $the_recent->have_posts() ) : $the_recent->the_post(); ?>
<div class="more-news">
<a href=""><?php the_title(); ?> </a>
</div>
<hr>
<?php endwhile ?>
<?php endif ?>
</code></pre>
| [
{
"answer_id": 252162,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Seems like this might be related to this ticket <a href=\"https://core.trac.wordpress.org/ticket/39552\">... | 2017/01/11 | [
"https://wordpress.stackexchange.com/questions/252150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63922/"
] | I have a sidebar with all my post the page only displays one post at a time. I want to display the post that is clicked from the sidebar.
This is the single post display
```
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 1
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1 class=""><?php the_title(); ?></h1>
<div class="the-date"><p><br><?php the_time('F jS, Y') ?></p></div>
<div class=""><p><?php the_content(); ?></p></div>
<?php endwhile ?>
<?php endif ?>
```
This is the side bar displaying post i want to populate the post area
```
<?php
$recent_args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'offset' => 1
);
$the_recent = new WP_Query( $recent_args );
if ( $the_recent->have_posts() ) : ?>
<?php while ( $the_recent->have_posts() ) : $the_recent->the_post(); ?>
<div class="more-news">
<a href=""><?php the_title(); ?> </a>
</div>
<hr>
<?php endwhile ?>
<?php endif ?>
``` | In WordPress 4.7.1 [a change was introduced](https://core.trac.wordpress.org/changeset/39831) that checks for the real mime type of an uploaded file. This breaks uploading file types like SVG or DOCX. There already exist tickets for this issue in WordPress Core, where you can read more about this:
* Some Non-image files fail to upload after 4.7.1 (<https://core.trac.wordpress.org/ticket/39550>)
* SVG upload support broken in 4.7.1 (<https://core.trac.wordpress.org/ticket/39552>)
A **temporary** and recommended workaround (for the time until this issue is fixed) is the following plugin:
[**Disable Real MIME Check**](https://wordpress.org/plugins/disable-real-mime-check/)
If you don’t want to use that plugin, here’s the same functionality:
```
add_filter( 'wp_check_filetype_and_ext', function($data, $file, $filename, $mimes) {
global $wp_version;
if ( '4.7.2' !== $wp_version ) {
return $data;
}
$filetype = wp_check_filetype( $filename, $mimes );
return [
'ext' => $filetype['ext'],
'type' => $filetype['type'],
'proper_filename' => $data['proper_filename']
];
}, 10, 4 );
```
Notice that this snipped has a version check included to disable the fix as soon as WordPress is updated.
**Edit**
The issue was initially set to be fixed in 4.7.2. But since [4.7.2 was an urgent security release](https://wordpress.org/news/2017/01/wordpress-4-7-2-security-release/), the fix didn’t make it into that version. It’s now supposed to be fixed in 4.7.3. |
252,171 | <p>I'm having trouble trying to display the current logged in author's first_name even if they haven't published a custom post outside the loop. Could someone get me started please.</p>
| [
{
"answer_id": 252175,
"author": "Eckstein",
"author_id": 23492,
"author_profile": "https://wordpress.stackexchange.com/users/23492",
"pm_score": 1,
"selected": false,
"text": "<p>This should do it:</p>\n\n<pre><code>$user = get_current_user_id();\n$userdata = get_userdata($user);\n$firs... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252171",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] | I'm having trouble trying to display the current logged in author's first\_name even if they haven't published a custom post outside the loop. Could someone get me started please. | author's name or logged in user's name?
can use `global $current_user;` or `wp_get_current_user();` if the user is logged in.
```
if( is_user_logged_in() ) {
$current_user = wp_get_current_user();
echo $current_user->user_firstname;
}
```
for specific user role you can check `$current_user->roles` array.
Reference:
<https://codex.wordpress.org/Function_Reference/wp_get_current_user>
<https://codex.wordpress.org/Function_Reference/get_currentuserinfo> |
252,253 | <p>I updated Wordpress to 4.7.1 and cant upload SVG anymore.</p>
<p>I had a function in my functions.php file </p>
<pre><code>function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
</code></pre>
<p>but it also dont help now.</p>
| [
{
"answer_id": 252324,
"author": "Don-Silvermann",
"author_id": 110815,
"author_profile": "https://wordpress.stackexchange.com/users/110815",
"pm_score": 4,
"selected": true,
"text": "<p>Per the thread below, a <strong>temporary solution</strong> would be to add this code to your wp-conf... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252253",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110781/"
] | I updated Wordpress to 4.7.1 and cant upload SVG anymore.
I had a function in my functions.php file
```
function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
```
but it also dont help now. | Per the thread below, a **temporary solution** would be to add this code to your wp-config file:
```
define( 'ALLOW_UNFILTERED_UPLOADS', true );
```
<https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/> |
252,255 | <p>I am trying to learn TDD and am struggling with creating factories for custom objects. For instance, if I have a custom user type and all users of that type must have a specific capability, it's cumbersome to use the WP_UnitTest factory to create a user and then add the capability manually in each test before using the object. Because I need to use these objects in a variety of test files, it would be redundant to have a factory function in each test file/class, and it's a pain to manually implement all four variations of the factory methods (create, create_and_get, create_many, and create_and_get_many).</p>
<p>What is the best way to create a factory for unit test objects like this?</p>
| [
{
"answer_id": 252324,
"author": "Don-Silvermann",
"author_id": 110815,
"author_profile": "https://wordpress.stackexchange.com/users/110815",
"pm_score": 4,
"selected": true,
"text": "<p>Per the thread below, a <strong>temporary solution</strong> would be to add this code to your wp-conf... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252255",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38193/"
] | I am trying to learn TDD and am struggling with creating factories for custom objects. For instance, if I have a custom user type and all users of that type must have a specific capability, it's cumbersome to use the WP\_UnitTest factory to create a user and then add the capability manually in each test before using the object. Because I need to use these objects in a variety of test files, it would be redundant to have a factory function in each test file/class, and it's a pain to manually implement all four variations of the factory methods (create, create\_and\_get, create\_many, and create\_and\_get\_many).
What is the best way to create a factory for unit test objects like this? | Per the thread below, a **temporary solution** would be to add this code to your wp-config file:
```
define( 'ALLOW_UNFILTERED_UPLOADS', true );
```
<https://wordpress.org/support/topic/wp-4-7-1-kills-svg/page/3/> |
252,258 | <p>I have a shortcode that takes 1 argument for post category slug and returns and list of posts.</p>
<pre><code> //[list-products] creates the product table in the wholesale page, can be used to create a table list of any category
function list_products_func ( $atts ) {
$a = shortcode_atts( array (
'category' => '',
), $atts);
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $a['category']
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query( $args );
echo "<table>";
while ( $products->have_posts() ) {
$products->the_post();
$product = new WC_Product(get_the_ID());
?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a></td>
<td>
<?php echo get_the_excerpt(); ?>
</td>
<td>
<?php echo $product->get_price_html(); ?>
</td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td>
<?php echo woocommerce_template_loop_add_to_cart(); ?>
</td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode ( 'list_products' , 'list_products_func' );
</code></pre>
<p>I'd like it to be able to take any number of categories and return the posts that match BOTH categories. In this use case, it is being used by a coffee distributor to show WooCommerce products that have a category of <code>wholesale</code> and one of their coffee subcategories <code>distinct-well-defined</code> or whatever.</p>
<p>The way it is used is <code>[list-products CAT1 CAT2]</code></p>
<p>I tried just typing the shortcode with commas and hoping the code interpreted that correctly, but that didn't work.</p>
<p>Any help would be appreciated.</p>
<h1>Update</h1>
<p>It turns out I actually need it to filter products so it only shows products that have both categories, not showing all products in both categories.</p>
| [
{
"answer_id": 252263,
"author": "Robbert",
"author_id": 25834,
"author_profile": "https://wordpress.stackexchange.com/users/25834",
"pm_score": 2,
"selected": true,
"text": "<p>Maybe you can make it so that you can use the shortcode like [list-products categories=\"1,2,3\"], and then ex... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110308/"
] | I have a shortcode that takes 1 argument for post category slug and returns and list of posts.
```
//[list-products] creates the product table in the wholesale page, can be used to create a table list of any category
function list_products_func ( $atts ) {
$a = shortcode_atts( array (
'category' => '',
), $atts);
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $a['category']
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query( $args );
echo "<table>";
while ( $products->have_posts() ) {
$products->the_post();
$product = new WC_Product(get_the_ID());
?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a></td>
<td>
<?php echo get_the_excerpt(); ?>
</td>
<td>
<?php echo $product->get_price_html(); ?>
</td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td>
<?php echo woocommerce_template_loop_add_to_cart(); ?>
</td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode ( 'list_products' , 'list_products_func' );
```
I'd like it to be able to take any number of categories and return the posts that match BOTH categories. In this use case, it is being used by a coffee distributor to show WooCommerce products that have a category of `wholesale` and one of their coffee subcategories `distinct-well-defined` or whatever.
The way it is used is `[list-products CAT1 CAT2]`
I tried just typing the shortcode with commas and hoping the code interpreted that correctly, but that didn't work.
Any help would be appreciated.
Update
======
It turns out I actually need it to filter products so it only shows products that have both categories, not showing all products in both categories. | Maybe you can make it so that you can use the shortcode like [list-products categories="1,2,3"], and then explode them as an array to insert them as your terms?
```
<?php
function list_products_func($atts) {
$a = shortcode_atts(array(
'categories' => '',
), $atts);
// Check for multiple categories by comma
if ( strpos( $a['categories'], ',' ) !== false ) {
$terms = explode( $a['categories'] );
} else {
$terms = $a['categories'];
}
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms // Your exploded terms array
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query($args);
echo "<table>";
while ($products->have_posts()) {
$products->the_post();
$product = new WC_Product(get_the_ID()); ?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php echo get_the_excerpt(); ?></td>
<td><?php echo $product->get_price_html(); ?></td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode('list_products', 'list_products_func');
?>
``` |
252,260 | <p>For some reason, I am battling to make sense of everything. This is my code on paste bin: <a href="http://pastebin.com/dJxGS6x6" rel="nofollow noreferrer">http://pastebin.com/dJxGS6x6</a></p>
<p>I want to be able to retrieve the options that are saved in the fields. This does not return anything: </p>
<pre><code><a href="<?php echo get_option('contact_details_vimeo_render'); ?>" target="_blank">
<i class="fa fa-vimeo" aria-hidden="true"></i>
</a>
</code></pre>
<p>I basically want to be able to retrieve the stored data as desired. </p>
| [
{
"answer_id": 252263,
"author": "Robbert",
"author_id": 25834,
"author_profile": "https://wordpress.stackexchange.com/users/25834",
"pm_score": 2,
"selected": true,
"text": "<p>Maybe you can make it so that you can use the shortcode like [list-products categories=\"1,2,3\"], and then ex... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | For some reason, I am battling to make sense of everything. This is my code on paste bin: <http://pastebin.com/dJxGS6x6>
I want to be able to retrieve the options that are saved in the fields. This does not return anything:
```
<a href="<?php echo get_option('contact_details_vimeo_render'); ?>" target="_blank">
<i class="fa fa-vimeo" aria-hidden="true"></i>
</a>
```
I basically want to be able to retrieve the stored data as desired. | Maybe you can make it so that you can use the shortcode like [list-products categories="1,2,3"], and then explode them as an array to insert them as your terms?
```
<?php
function list_products_func($atts) {
$a = shortcode_atts(array(
'categories' => '',
), $atts);
// Check for multiple categories by comma
if ( strpos( $a['categories'], ',' ) !== false ) {
$terms = explode( $a['categories'] );
} else {
$terms = $a['categories'];
}
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms // Your exploded terms array
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query($args);
echo "<table>";
while ($products->have_posts()) {
$products->the_post();
$product = new WC_Product(get_the_ID()); ?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php echo get_the_excerpt(); ?></td>
<td><?php echo $product->get_price_html(); ?></td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode('list_products', 'list_products_func');
?>
``` |
252,262 | <p>I am just beginning a page, and for my current purposes it seems that the only extra things I need are a couple of extra fields for posts of a certain category. Because I only need to add a little information, I think that it might be appropriate to give posts belonging to this category custom fields using Advanced Custom Fields (aka ACF). However, I was thinking that later I might discover it is better to use custom post types, that have the fields built into the structure of the custom post type. </p>
<p>For example, imagine I originally start with normal posts, and I assign them all to the category of "movie". I give them each post in the category movie the custom field called "director" and populate it with the appropriate director. Then, later, if I want to create a custom post type, that has the field "director" as part of the custom post-type I create called "MovieType", could I easily transfer the directors in the custom fields for every old "normal post" of category "movie" to be imported to the new custom post type?</p>
<p>I am concerned it might not be easy to export this data to a custom post type later and I don't want to have to manually copy/paste or enter all the fields from my custom fields to the fields of the new custom post type. </p>
<p><strong>The question: what is the easiest way to convert standard posts with custom fields into a new custom post type, AND to import/keep the data originally assigned to each post from the custom field into the native field of a new post type? Can this be done automatically?</strong></p>
<p>Thanks!</p>
| [
{
"answer_id": 252263,
"author": "Robbert",
"author_id": 25834,
"author_profile": "https://wordpress.stackexchange.com/users/25834",
"pm_score": 2,
"selected": true,
"text": "<p>Maybe you can make it so that you can use the shortcode like [list-products categories=\"1,2,3\"], and then ex... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252262",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
] | I am just beginning a page, and for my current purposes it seems that the only extra things I need are a couple of extra fields for posts of a certain category. Because I only need to add a little information, I think that it might be appropriate to give posts belonging to this category custom fields using Advanced Custom Fields (aka ACF). However, I was thinking that later I might discover it is better to use custom post types, that have the fields built into the structure of the custom post type.
For example, imagine I originally start with normal posts, and I assign them all to the category of "movie". I give them each post in the category movie the custom field called "director" and populate it with the appropriate director. Then, later, if I want to create a custom post type, that has the field "director" as part of the custom post-type I create called "MovieType", could I easily transfer the directors in the custom fields for every old "normal post" of category "movie" to be imported to the new custom post type?
I am concerned it might not be easy to export this data to a custom post type later and I don't want to have to manually copy/paste or enter all the fields from my custom fields to the fields of the new custom post type.
**The question: what is the easiest way to convert standard posts with custom fields into a new custom post type, AND to import/keep the data originally assigned to each post from the custom field into the native field of a new post type? Can this be done automatically?**
Thanks! | Maybe you can make it so that you can use the shortcode like [list-products categories="1,2,3"], and then explode them as an array to insert them as your terms?
```
<?php
function list_products_func($atts) {
$a = shortcode_atts(array(
'categories' => '',
), $atts);
// Check for multiple categories by comma
if ( strpos( $a['categories'], ',' ) !== false ) {
$terms = explode( $a['categories'] );
} else {
$terms = $a['categories'];
}
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms // Your exploded terms array
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query($args);
echo "<table>";
while ($products->have_posts()) {
$products->the_post();
$product = new WC_Product(get_the_ID()); ?>
<tr class="product-list-item">
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php echo get_the_excerpt(); ?></td>
<td><?php echo $product->get_price_html(); ?></td>
<td>
<?php echo woocommerce_quantity_input(
array(
'min_value' => 1,
'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity(),
)); ?>
</td>
<td><?php echo woocommerce_template_loop_add_to_cart(); ?></td>
</tr>
<?php
}
echo "</table>";
}
add_shortcode('list_products', 'list_products_func');
?>
``` |
252,277 | <p>I'm still a noob with php but I'm trying to display a different layout for my Wordpress webpage for a single post id. </p>
<p>I thought it would have been simple but I've tried a quiet few variations of the code below. Including <code>is_singular</code> and without the <code>$post</code> etc. and I've ran out of inspiration. What can I do? What do I need to look for? Can anyone help me out?</p>
<pre><code><?php
if (is_single ($post = '2578')) {
get_template_part('partials/content', 'challenge');
}
elseif (is_single ($post = '')) {
get_template_part('partials/challenge/content', 'challenge-2');
get_template_part('partials/challenge/content', 'categories');
get_template_part('partials/challenge/content', 'snake-checklist');
get_template_part('partials/challenge/content', 'timeline');
}?>
</code></pre>
| [
{
"answer_id": 252286,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": false,
"text": "<p>This looks almost correct. Let's have a look at <a href=\"https://developer.wordpress.org/reference/functio... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252277",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110792/"
] | I'm still a noob with php but I'm trying to display a different layout for my Wordpress webpage for a single post id.
I thought it would have been simple but I've tried a quiet few variations of the code below. Including `is_singular` and without the `$post` etc. and I've ran out of inspiration. What can I do? What do I need to look for? Can anyone help me out?
```
<?php
if (is_single ($post = '2578')) {
get_template_part('partials/content', 'challenge');
}
elseif (is_single ($post = '')) {
get_template_part('partials/challenge/content', 'challenge-2');
get_template_part('partials/challenge/content', 'categories');
get_template_part('partials/challenge/content', 'snake-checklist');
get_template_part('partials/challenge/content', 'timeline');
}?>
``` | This looks almost correct. Let's have a look at [`is_single()`](https://developer.wordpress.org/reference/functions/is_single/):
>
> Works for any post type, **except attachments and pages**...
>
>
>
So if the given ID isn't that of a `page` or `attachment` post type then you can use the function as so:
```
if( is_single( 2578 ) ) {
/* ... */
} else {
/* ... */
}
```
Otherwise, if the ID is a `page` post type you can use [`is_page()`](https://developer.wordpress.org/reference/functions/is_page/)
```
if( is_page( 2578 ) ) {
/* ... */
}
```
Should the ID be that of an `attachment` page you may use [`is_attachment()`](https://developer.wordpress.org/reference/functions/is_attachment/)
```
if( is_attachment( 2578 ) ) {
/* ... */
}
```
Finally, if you're unsure of the post type you could check against the `global $post` object, assuming it is correct:
```
global $post;
if( is_object( $post ) && 2578 == $post->ID ) {
/* ... */
}
``` |
252,300 | <p>I'm very new to WordPress Development and I'm attempting to make a custom post type business directory style plugin in my plugins folder for my site, but everytime I activate it I get the white screen of death over my entire web site. I've definitely tracked it down to this plugin but I can't see what I've done that's causing it.</p>
<pre><code><?php
/*
Plugin Name: Special Coffee CPT
Plugin URI: http://danijoypractice.x10host.com
Description: This plugin creates a custom post type & template page
Author: Danielle Rautiainen
Version: 1.0
Author URI: http://danijoypractice.x10host.com
*/
add_action('init', 'local_business_directory_register');
function local_business_directory_register() {
$args = array(
'label' => __('Business Directory'),
'singular_label' => __('Business'),
'public' => true,
'taxonomies' => array('category'),
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'supports' => array('title', 'editor', ),
'rewrite' => array('slug' => 'businesses', 'with_front' => false),
);
}
register_post_type( 'businesses' , $args );
register_taxonomy("business-type", array("businesses"), array(
"hierarchical" => true,
"label" => "Business Type",
"singular_label" => "Business Type",
"rewrite" => true
)
);
add_action("admin_init", "local_business_directory_meta");
function local_business_directory_meta ()
{
add_meta_box("business-meta", "Business Options", "local_business_directory_options", "businesses", "normal", "high");
}
function local_business_directory_options()
{
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
$custom = get_post_custom($post->ID);
$address = $custom["address"][0];
$website = $custom["website"][0];
$phone = $custom["phone"][0];
?>
<style type="text/css">
<?php include('business-directory.css'); ?>
</style>
<div class="business_directory_extras">
<?php $website= ($website == "") ? "http://" : $website; ?>
<div>
<label>Website:</label>
<input name="website" value="<?php echo $website; ?>" />
</div>
<div>
<label>Phone:</label>
<input name="phone" value="<?php echo $phone; ?>" />
</div>
<div>
<label>Address:</label>
<textarea name="address"><?php echo $address; ?>" /></textarea>
</div>
</div>
<?php
}
add_action('save_post', 'local_business_directory_save_extras');
function business_manager_save_extras(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return $post_id;
}else{
update_post_meta($post->ID, "website", $_POST["website"]);
update_post_meta($post->ID, "address", $_POST["address"]);
update_post_meta($post->ID, "phone", $_POST["phone"]);
}
}
?>
</code></pre>
<p>Am I missing something? Any help would be very appreciated!</p>
| [
{
"answer_id": 252286,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": false,
"text": "<p>This looks almost correct. Let's have a look at <a href=\"https://developer.wordpress.org/reference/functio... | 2017/01/12 | [
"https://wordpress.stackexchange.com/questions/252300",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110800/"
] | I'm very new to WordPress Development and I'm attempting to make a custom post type business directory style plugin in my plugins folder for my site, but everytime I activate it I get the white screen of death over my entire web site. I've definitely tracked it down to this plugin but I can't see what I've done that's causing it.
```
<?php
/*
Plugin Name: Special Coffee CPT
Plugin URI: http://danijoypractice.x10host.com
Description: This plugin creates a custom post type & template page
Author: Danielle Rautiainen
Version: 1.0
Author URI: http://danijoypractice.x10host.com
*/
add_action('init', 'local_business_directory_register');
function local_business_directory_register() {
$args = array(
'label' => __('Business Directory'),
'singular_label' => __('Business'),
'public' => true,
'taxonomies' => array('category'),
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'supports' => array('title', 'editor', ),
'rewrite' => array('slug' => 'businesses', 'with_front' => false),
);
}
register_post_type( 'businesses' , $args );
register_taxonomy("business-type", array("businesses"), array(
"hierarchical" => true,
"label" => "Business Type",
"singular_label" => "Business Type",
"rewrite" => true
)
);
add_action("admin_init", "local_business_directory_meta");
function local_business_directory_meta ()
{
add_meta_box("business-meta", "Business Options", "local_business_directory_options", "businesses", "normal", "high");
}
function local_business_directory_options()
{
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
$custom = get_post_custom($post->ID);
$address = $custom["address"][0];
$website = $custom["website"][0];
$phone = $custom["phone"][0];
?>
<style type="text/css">
<?php include('business-directory.css'); ?>
</style>
<div class="business_directory_extras">
<?php $website= ($website == "") ? "http://" : $website; ?>
<div>
<label>Website:</label>
<input name="website" value="<?php echo $website; ?>" />
</div>
<div>
<label>Phone:</label>
<input name="phone" value="<?php echo $phone; ?>" />
</div>
<div>
<label>Address:</label>
<textarea name="address"><?php echo $address; ?>" /></textarea>
</div>
</div>
<?php
}
add_action('save_post', 'local_business_directory_save_extras');
function business_manager_save_extras(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return $post_id;
}else{
update_post_meta($post->ID, "website", $_POST["website"]);
update_post_meta($post->ID, "address", $_POST["address"]);
update_post_meta($post->ID, "phone", $_POST["phone"]);
}
}
?>
```
Am I missing something? Any help would be very appreciated! | This looks almost correct. Let's have a look at [`is_single()`](https://developer.wordpress.org/reference/functions/is_single/):
>
> Works for any post type, **except attachments and pages**...
>
>
>
So if the given ID isn't that of a `page` or `attachment` post type then you can use the function as so:
```
if( is_single( 2578 ) ) {
/* ... */
} else {
/* ... */
}
```
Otherwise, if the ID is a `page` post type you can use [`is_page()`](https://developer.wordpress.org/reference/functions/is_page/)
```
if( is_page( 2578 ) ) {
/* ... */
}
```
Should the ID be that of an `attachment` page you may use [`is_attachment()`](https://developer.wordpress.org/reference/functions/is_attachment/)
```
if( is_attachment( 2578 ) ) {
/* ... */
}
```
Finally, if you're unsure of the post type you could check against the `global $post` object, assuming it is correct:
```
global $post;
if( is_object( $post ) && 2578 == $post->ID ) {
/* ... */
}
``` |
252,328 | <p>I have upgraded my WordPress to <code>4.7.1</code>, and after that I've tried to enumerate users through REST API, which should be fixed, but I was able to retrieve users.</p>
<pre><code>https://mywebsite.com/wp-json/wp/v2/users
</code></pre>
<p>Output:</p>
<pre><code>[{"id":1,"name":"admin","url":"","description":"","link":"https:\/\/mywebsite\/author\/admin\/","slug":"admin","avatar_urls":{"24": ...
</code></pre>
<p>Changelog from latest version:</p>
<blockquote>
<p>The REST API exposed user data for all users who had authored a post
of a public post type. WordPress 4.7.1 limits this to only post types
which have specified that they should be shown within the REST API.
Reported by Krogsgard and Chris Jean.</p>
</blockquote>
<p>After installing plugin <code>Disable REST API</code>, it seems that everything is working fine, but I don't like to use for every little thing plugin.</p>
<p>The output after using plugin is:</p>
<pre><code>{"code":"rest_cannot_access","message":"Only authenticated users can access the REST API.","data":{"status":401}}
</code></pre>
<p>How can I fix this issue without using plugin, or why even after upgrading this stil exist?</p>
<p><strong>EDIT 30.9.2017</strong></p>
<p>I realized that there is a conflict between <code>contact 7</code> plugin and <code>Disable REST API</code> and that will give you <code>401 unauthorized</code> error.</p>
<p>When you try to send a message through <code>contact 7</code> form, it will make a request </p>
<pre><code>wp-json/contact-form-7/v1/contact-forms/258/feedback
</code></pre>
<p>and disabling that is not a good idea.</p>
| [
{
"answer_id": 254251,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 6,
"selected": true,
"text": "<p>This code snippet will hide the users, posts, and comments endpoint results and give 404 as the result, whi... | 2017/01/13 | [
"https://wordpress.stackexchange.com/questions/252328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91550/"
] | I have upgraded my WordPress to `4.7.1`, and after that I've tried to enumerate users through REST API, which should be fixed, but I was able to retrieve users.
```
https://mywebsite.com/wp-json/wp/v2/users
```
Output:
```
[{"id":1,"name":"admin","url":"","description":"","link":"https:\/\/mywebsite\/author\/admin\/","slug":"admin","avatar_urls":{"24": ...
```
Changelog from latest version:
>
> The REST API exposed user data for all users who had authored a post
> of a public post type. WordPress 4.7.1 limits this to only post types
> which have specified that they should be shown within the REST API.
> Reported by Krogsgard and Chris Jean.
>
>
>
After installing plugin `Disable REST API`, it seems that everything is working fine, but I don't like to use for every little thing plugin.
The output after using plugin is:
```
{"code":"rest_cannot_access","message":"Only authenticated users can access the REST API.","data":{"status":401}}
```
How can I fix this issue without using plugin, or why even after upgrading this stil exist?
**EDIT 30.9.2017**
I realized that there is a conflict between `contact 7` plugin and `Disable REST API` and that will give you `401 unauthorized` error.
When you try to send a message through `contact 7` form, it will make a request
```
wp-json/contact-form-7/v1/contact-forms/258/feedback
```
and disabling that is not a good idea. | This code snippet will hide the users, posts, and comments endpoint results and give 404 as the result, while the rest of the API calls keep running as they were.
**::UPDATE::**
```
add_filter('rest_endpoints', function(){
$toRemove = ['users', 'posts', 'comments'];
foreach($toRemove as $val)
{
if (isset($endpoints['/wp/v2/'.$val])) {
unset($endpoints['/wp/v2/'.$val]);
}
if(isset($endpoints['/wp/v2/'.$val.'/(?P<id>[\d]+)'])) {
unset($endpoints['/wp/v2/'.$val.'/(?P<id>[\d]+)']);
}
}
return $endpoints;
});
```
**::UPDATE::**
This snippet will remove all the default endpoints.
`<?php remove_action('rest_api_init', 'create_initial_rest_routes', 99); ?>` |
252,369 | <p>What are the proper filter/hooks to modify the wp-login.php?action=logout confirmation page</p>
<p><a href="https://i.stack.imgur.com/toDrN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/toDrN.png" alt="enter image description here" /></a>When you logout of your site using <strong>yoursite.com/wp-login.php?action=logout</strong> , You will go to a standard page WordPress logout page that has the following text:</p>
<blockquote>
<p>You are attempting to log out of "Your Site"</p>
<p>Do you really want to log out?</p>
</blockquote>
<p>I do not see any hooks/filters to modify it, I have checked from here: <a href="https://codex.wordpress.org/Function_Reference/wp_logout_url" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/wp_logout_url</a></p>
<p>What is the best way to edit this page?</p>
| [
{
"answer_id": 252370,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user ... | 2017/01/13 | [
"https://wordpress.stackexchange.com/questions/252369",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60720/"
] | What are the proper filter/hooks to modify the wp-login.php?action=logout confirmation page
[](https://i.stack.imgur.com/toDrN.png)When you logout of your site using **yoursite.com/wp-login.php?action=logout** , You will go to a standard page WordPress logout page that has the following text:
>
> You are attempting to log out of "Your Site"
>
>
> Do you really want to log out?
>
>
>
I do not see any hooks/filters to modify it, I have checked from here: <https://codex.wordpress.org/Function_Reference/wp_logout_url>
What is the best way to edit this page? | Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs.
```
<?php wp_loginout( $redirect, $echo ); ?>
```
<https://codex.wordpress.org/Function_Reference/wp_loginout>
This might helps you. |
252,379 | <p>I developed a plugin which processes data following user input into a number of forms on the front end. The field types within the forms and the data input varies significantly.</p>
<p>To process the data, I hook into <code>init</code> and use the following function;</p>
<pre><code>function mh_post_actions() {
if ( isset( $_POST['mh_action'] ) ) {
do_action( 'mh_' . sanitize_text_field( $_POST['mh_action'] ), $_POST );
}
} // mh_post_actions
add_action( 'init', 'mh_post_actions' );
</code></pre>
<p>Validation and sanitizing then takes place in the resulting functions hooked into <code>mh_*</code>.</p>
<p>However, recently I took the decision to publish the plugin via the WordPress.org repo.</p>
<p>On review, my code has been rejected stating that per the guidelines, I need to validate and sanitize the data before any WordPress processing takes place.</p>
<p>That is fine, but as mentioned the data can be anything, array, int, str, url, email etc...</p>
<p>I'd like to keep the function I have as it works well for me, so wondered if there was any easier way to sanitize general $_POST data which I could add to the above function in order to meet the guidelines?</p>
| [
{
"answer_id": 252370,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user ... | 2017/01/13 | [
"https://wordpress.stackexchange.com/questions/252379",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69112/"
] | I developed a plugin which processes data following user input into a number of forms on the front end. The field types within the forms and the data input varies significantly.
To process the data, I hook into `init` and use the following function;
```
function mh_post_actions() {
if ( isset( $_POST['mh_action'] ) ) {
do_action( 'mh_' . sanitize_text_field( $_POST['mh_action'] ), $_POST );
}
} // mh_post_actions
add_action( 'init', 'mh_post_actions' );
```
Validation and sanitizing then takes place in the resulting functions hooked into `mh_*`.
However, recently I took the decision to publish the plugin via the WordPress.org repo.
On review, my code has been rejected stating that per the guidelines, I need to validate and sanitize the data before any WordPress processing takes place.
That is fine, but as mentioned the data can be anything, array, int, str, url, email etc...
I'd like to keep the function I have as it works well for me, so wondered if there was any easier way to sanitize general $\_POST data which I could add to the above function in order to meet the guidelines? | Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs.
```
<?php wp_loginout( $redirect, $echo ); ?>
```
<https://codex.wordpress.org/Function_Reference/wp_loginout>
This might helps you. |
252,419 | <p>Is there a way to post content that does not move or remains "static" within different pages? I am trying to set a description of each of my pages on my blog to give the reader an intro about each page. Is this Possible?</p>
<p>Example:</p>
<p>This is how I would want my "Audio Stories" page to look....</p>
<p>(Page)Audio Stories
(Content) In this section you will find tales of random encounters with strangers from around the world.</p>
<p>blog post</p>
<p>blog post</p>
<p>blog post</p>
<p>etc..</p>
| [
{
"answer_id": 252370,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user ... | 2017/01/13 | [
"https://wordpress.stackexchange.com/questions/252419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110866/"
] | Is there a way to post content that does not move or remains "static" within different pages? I am trying to set a description of each of my pages on my blog to give the reader an intro about each page. Is this Possible?
Example:
This is how I would want my "Audio Stories" page to look....
(Page)Audio Stories
(Content) In this section you will find tales of random encounters with strangers from around the world.
blog post
blog post
blog post
etc.. | Its seems we don't have any hook to modify that page. But you can use alternative way and redirect user to a desire template and modify that template according to your needs.
```
<?php wp_loginout( $redirect, $echo ); ?>
```
<https://codex.wordpress.org/Function_Reference/wp_loginout>
This might helps you. |
252,426 | <p><strong>TLDR</strong>: While in the backend, I would like to add custom post type inside a menu page (which I can do). But I cannot order the resulting submenu pages.</p>
<hr>
<p>I have <strong>3 custom post types</strong> “A”, “B”, “C”, and I want to:</p>
<ol>
<li><strong>Group</strong> the 3 contents <strong>under one menu page</strong> called “My Custom Page”</li>
<li>When I click “My Custom Page”, being <strong>redirected to the content</strong> of “My Custom Page”, and <strong>not one of the custom post types</strong>.</li>
</ol>
<p>I accomplished the first half quite easilly: I created a menu pages as follows:</p>
<pre><code>add_menu_page('My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug');
</code></pre>
<p>And then, I set each custom post type like this:</p>
<pre><code>'show_in_menu'=> 'my-top-level-slug'
</code></pre>
<p>This allows me to successfully group my 3 custom post types under one single menu page. And <strong>here lies the problem</strong>: if I click on “My Custom Page”, I get redirected to the first custom post type (depending on the inclusion order) – I would like to click on “My Custom Page” and get redirected to said page (where I plan on list show stats, most viewed posts, etc), but instead a custom post type opens up, which I don’t really want.</p>
<p>I figured I could add a submenu page, but any submenu page I add gets included AFTER the custom post types (so at the bottom of the submenu pages list). So I’m wondering if is there a way to assign an order to those subpages, so that if I click over “My Custom Page”, it’s not gonna show a custom post type.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>After some searching, I found the following article on the Codex: <a href="https://developer.wordpress.org/reference/functions/add_submenu_page/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/add_submenu_page/</a> . By following this example and embeding this code:</p>
<pre><code>function wpdocs_register_my_custom_submenu_page() {
add_submenu_page(
'my-menu',
'My Custom Submenu Page',
'My Custom Submenu Page',
'manage_options',
'edit.php?post_type=CPT-NAME',
false
);
}
add_action('admin_menu', 'wpdocs_register_my_custom_submenu_page');
</code></pre>
<p>I'm able to accomplish the 2 points above (so the grouping works and when I click I get redirected to a review page). But - by doing so, once I enter inside a post (create or edit one, doesn't matter) the <strong>menu page does't result active</strong> anymore: if I hover on the menu page, it's marked in white as in active, but otherwise the menu & submenus are collapsed/closed.</p>
<p>The previous solution was working correctly (menu state wise), but didn't allow me to assign a custom page to “My Custom Page”. As for the second solution, it's vice versa (menu state is inactive while inside a post, but I can show “My Custom Page”).</p>
| [
{
"answer_id": 252428,
"author": "Cerere",
"author_id": 16281,
"author_profile": "https://wordpress.stackexchange.com/users/16281",
"pm_score": 3,
"selected": true,
"text": "<p>I found the answer. To make it short:</p>\n<h1>SOLUTION 1</h1>\n<p>If you want to simply add a custom post type... | 2017/01/13 | [
"https://wordpress.stackexchange.com/questions/252426",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16281/"
] | **TLDR**: While in the backend, I would like to add custom post type inside a menu page (which I can do). But I cannot order the resulting submenu pages.
---
I have **3 custom post types** “A”, “B”, “C”, and I want to:
1. **Group** the 3 contents **under one menu page** called “My Custom Page”
2. When I click “My Custom Page”, being **redirected to the content** of “My Custom Page”, and **not one of the custom post types**.
I accomplished the first half quite easilly: I created a menu pages as follows:
```
add_menu_page('My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug');
```
And then, I set each custom post type like this:
```
'show_in_menu'=> 'my-top-level-slug'
```
This allows me to successfully group my 3 custom post types under one single menu page. And **here lies the problem**: if I click on “My Custom Page”, I get redirected to the first custom post type (depending on the inclusion order) – I would like to click on “My Custom Page” and get redirected to said page (where I plan on list show stats, most viewed posts, etc), but instead a custom post type opens up, which I don’t really want.
I figured I could add a submenu page, but any submenu page I add gets included AFTER the custom post types (so at the bottom of the submenu pages list). So I’m wondering if is there a way to assign an order to those subpages, so that if I click over “My Custom Page”, it’s not gonna show a custom post type.
---
**UPDATE**
After some searching, I found the following article on the Codex: <https://developer.wordpress.org/reference/functions/add_submenu_page/> . By following this example and embeding this code:
```
function wpdocs_register_my_custom_submenu_page() {
add_submenu_page(
'my-menu',
'My Custom Submenu Page',
'My Custom Submenu Page',
'manage_options',
'edit.php?post_type=CPT-NAME',
false
);
}
add_action('admin_menu', 'wpdocs_register_my_custom_submenu_page');
```
I'm able to accomplish the 2 points above (so the grouping works and when I click I get redirected to a review page). But - by doing so, once I enter inside a post (create or edit one, doesn't matter) the **menu page does't result active** anymore: if I hover on the menu page, it's marked in white as in active, but otherwise the menu & submenus are collapsed/closed.
The previous solution was working correctly (menu state wise), but didn't allow me to assign a custom page to “My Custom Page”. As for the second solution, it's vice versa (menu state is inactive while inside a post, but I can show “My Custom Page”). | I found the answer. To make it short:
SOLUTION 1
==========
If you want to simply add a custom post type to a menu item, go with solution number one (which involves creating a menu page with `add_menu_page`and setting `'show_in_menu=>'` to your menu page slug). It works, but if you click on your newly created menu page, you will get redirected to the first CPT (any subpage will get pushed at the end of the list).
SOLUTION 2
==========
If you want to group you custom post types, click on your menu page and end up on a subpage, then go with solution number 2 (see update above): set `'show_in_menu=> false'`, then create a function like this:
```
function create_menupages_252428() {
// https://developer.wordpress.org/reference/functions/add_menu_page/
add_menu_page(
'Page', // Page title
'Page', // Menu title
'manage_options', // Capability
'page', // Slug
'mycustompage', // Function name
'dashicons-format-aside', // Slug
1 // Order
);
// https://developer.wordpress.org/reference/functions/add_submenu_page/
add_submenu_page(
'page', // Parent slug
'subpage', // Page title
'subpage', // Menu title
'manage_options', // Capability
'edit.php?post_type=CPT', // Slug
false // Function
);
}
add_action('admin_menu', 'create_menupages_252428');
```
Once done, if you want to show the menu page as active while operating on your custom post type,
```
function menu_active_252428() {
global $parent_file, $post_type;
if ( $post_type == 'CPT' ) {
$parent_file = 'page';
}
}
add_action( 'admin_head', 'menu_active_252428' );
```
If by any chance you find a better way, feel free to add/correct my solution! |
252,431 | <p>I'm hooking into <code>the_editor_content</code> to add a signature to new posts. However, when a user edits their post the content is lost and replaced with the signature. </p>
<p>I tried something like the following in the hopes that the <code>the_editor_content</code> would only fire for new posts: </p>
<pre><code>add_action( 'new_to_publish', 'my_new_post');
function my_new_post( $post ) {
function my_editor_content( $content ) {
$current_user = wp_get_current_user();
$author_name = $current_user->display_name;
$editor_content = '<br><br><br><br><br>--<br>'.$author_name;
return $editor_content;
}
add_filter( 'the_editor_content', 'my_editor_content', 'tinymce' );
}
</code></pre>
<p>But it isn't working, I don't get the signature for new posts or any posts. Can this even be done this way? Note that <code>my_editor_content</code> works fine by itself.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 252445,
"author": "Mike",
"author_id": 69112,
"author_profile": "https://wordpress.stackexchange.com/users/69112",
"pm_score": 1,
"selected": false,
"text": "<p>OK, so the <code>new_to_publish</code> hook is probably not the right hook to use here.</p>\n\n<p>The <code>stat... | 2017/01/13 | [
"https://wordpress.stackexchange.com/questions/252431",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98236/"
] | I'm hooking into `the_editor_content` to add a signature to new posts. However, when a user edits their post the content is lost and replaced with the signature.
I tried something like the following in the hopes that the `the_editor_content` would only fire for new posts:
```
add_action( 'new_to_publish', 'my_new_post');
function my_new_post( $post ) {
function my_editor_content( $content ) {
$current_user = wp_get_current_user();
$author_name = $current_user->display_name;
$editor_content = '<br><br><br><br><br>--<br>'.$author_name;
return $editor_content;
}
add_filter( 'the_editor_content', 'my_editor_content', 'tinymce' );
}
```
But it isn't working, I don't get the signature for new posts or any posts. Can this even be done this way? Note that `my_editor_content` works fine by itself.
Thanks in advance. | I went with a different approach to solve this (probably not the cleanest one but it works for me).
I parsed the current url and added the signature with `the_editor_content` if on the page for new posts.
If on the page for editing posts, I parsed the url again to get the post id and return the post content in the editor.
I have frontend posting forms so it works. |
252,458 | <p>Trying to create a 'switching' blog template using home.php, controlled by 'Blog posts per page' setting in the admin area. If set to '1', it will show the single post template. Anything higher and it will display the archive template.</p>
<p><strong>In detail:</strong></p>
<p>The following code works, except for archive pagination (clicking older/newer posts changes the URL but displays first page content only).</p>
<pre><code><div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php // Get ppp for query
$ppp_val = get_option( 'posts_per_page' ); ?>
<?php
// Single post loop
$blogsingle_query = new WP_Query( $ppp_val <= 1 );
if($blogsingle_query->have_posts()) :
while($blogsingle_query->have_posts()) : $blogsingle_query->the_post();
get_template_part( 'parts/content', 'post' );
endwhile;
wp_reset_postdata();
the_post_navigation();
endif;
?>
<?php
// Multiple posts loop ( PAGINATION DOESN'T WORK )
$blogmulti_query = new WP_Query( $ppp_val > 1 );
if($blogmulti_query->have_posts()) :
while($blogmulti_query->have_posts()) : $blogmulti_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile;
wp_reset_postdata();
the_posts_navigation();
endif;
?>
</div><!-- #primary -->
</code></pre>
<p>In comparison, this alternate method does not work but feels like it might be a better track to follow?</p>
<pre><code><div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php $ppp_val = get_option( 'posts_per_page' ); ?>
<?php
$args=array(
'posts_per_page' => $ppp_val, // Get number of posts value
'meta_query' = array(
array(
'key' => 'posts_per_page', // Use this to compare
'compare' => '>',
'value' => 1,
'type' => 'NUMERIC',
)
),
);
$switch_query = new WP_Query( $args );
?>
<?php
if($switch_query->have_posts()) :
while($switch_query->have_posts()) : $switch_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile; else:
?>
<?php get_template_part( 'parts/content', 'post' ); ?>
<?php endif; ?>
</div><!-- #primary -->
</code></pre>
| [
{
"answer_id": 252459,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>You can control what template loads for any type of query via the <a href=\"https://developer.wordpress.org/themes/... | 2017/01/14 | [
"https://wordpress.stackexchange.com/questions/252458",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | Trying to create a 'switching' blog template using home.php, controlled by 'Blog posts per page' setting in the admin area. If set to '1', it will show the single post template. Anything higher and it will display the archive template.
**In detail:**
The following code works, except for archive pagination (clicking older/newer posts changes the URL but displays first page content only).
```
<div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php // Get ppp for query
$ppp_val = get_option( 'posts_per_page' ); ?>
<?php
// Single post loop
$blogsingle_query = new WP_Query( $ppp_val <= 1 );
if($blogsingle_query->have_posts()) :
while($blogsingle_query->have_posts()) : $blogsingle_query->the_post();
get_template_part( 'parts/content', 'post' );
endwhile;
wp_reset_postdata();
the_post_navigation();
endif;
?>
<?php
// Multiple posts loop ( PAGINATION DOESN'T WORK )
$blogmulti_query = new WP_Query( $ppp_val > 1 );
if($blogmulti_query->have_posts()) :
while($blogmulti_query->have_posts()) : $blogmulti_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile;
wp_reset_postdata();
the_posts_navigation();
endif;
?>
</div><!-- #primary -->
```
In comparison, this alternate method does not work but feels like it might be a better track to follow?
```
<div id="primary" class="content-area">
<h2>Switching Blog Template</h2>
<?php $ppp_val = get_option( 'posts_per_page' ); ?>
<?php
$args=array(
'posts_per_page' => $ppp_val, // Get number of posts value
'meta_query' = array(
array(
'key' => 'posts_per_page', // Use this to compare
'compare' => '>',
'value' => 1,
'type' => 'NUMERIC',
)
),
);
$switch_query = new WP_Query( $args );
?>
<?php
if($switch_query->have_posts()) :
while($switch_query->have_posts()) : $switch_query->the_post();
get_template_part( 'parts/content', 'archive' );
endwhile; else:
?>
<?php get_template_part( 'parts/content', 'post' ); ?>
<?php endif; ?>
</div><!-- #primary -->
``` | You can control what template loads for any type of query via the [Template Filters](https://developer.wordpress.org/themes/basics/template-hierarchy/#filter-hierarchy).
Here's an example using `home_template` that checks if `posts_per_page` is equal to `1`, and loads `single.php` in that case.
```
function wpd_home_template( $home_template = '' ){
if( get_option( 'posts_per_page' ) == 1 ){
$home_template = locate_template( 'single.php', false );
}
return $home_template;
}
add_filter( 'home_template', 'wpd_home_template' );
``` |
252,532 | <p>After upgrading to php 5.6.4 my widgets file causes:</p>
<p><code>Parse error: syntax error, unexpected 'class' (T_CLASS) in /home/path/fss-widgets.php on line 1</code></p>
<p>I'm mystified - several hours research has yielded nothing. The problem doesn't appear to be quoting, escaping, or anything else you would expect in this situation and the code looks ok to me.</p>
<pre><code><?php
/*
Plugin Name: FSS Vacancy Widget
Plugin URI: http://www.url.com/
Description: Shows recent vacancies
Author: Name
Version: 1.0
Author URI: http://www.url.com/
*/
class FSSVacancyWidget extends WP_Widget
{
function FSSVacancyWidget()
{
$widget_ops = array('classname' => 'FSSVacancyWidget', 'description' => 'Displays Recent FSS Jobs on the homepage and all other pages' );
$this->WP_Widget('FSSVacancyWidget', 'FSS Vacancies', $widget_ops);
}
function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = $instance['title'];
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_numposts'); ?>">Number of Posts (Default is 10): <input class="widefat" id="<?php echo $this->get_field_id('fss_numposts'); ?>" name="<?php echo $this->get_field_name('fss_numposts'); ?>" type="text" value="<?php echo attribute_escape($fss_numposts); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_vacurl'); ?>">Vacancy URL: <input class="widefat" id="<?php echo $this->get_field_id('fss_vacurl'); ?>" name="<?php echo $this->get_field_name('fss_vacurl'); ?>" type="text" value="<?php echo attribute_escape($fss_vacurl); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_morevac'); ?>">More Vacancies Title: <input class="widefat" id="<?php echo $this->get_field_id('fss_morevac'); ?>" name="<?php echo $this->get_field_name('fss_morevac'); ?>" type="text" value="<?php echo attribute_escape($fss_morevac); ?>" /></label></p>
<?php
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['fss_numposts'] = $new_instance['fss_numposts'];
$instance['fss_vacurl'] = $new_instance['fss_vacurl'];
$instance['fss_morevac'] = $new_instance['fss_morevac'];
return $instance;
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
/* User-selected settings. */
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
if (!empty($title))
echo $before_title . $title . $after_title;;
echo "<ul class='items'>";
query_posts( array( 'showposts' => $fss_numposts ) );
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo "<li><a href='".get_permalink()."'><span class='job-title'>".get_the_title()."</span><span class='job-date'>".get_the_date('d m Y')."</span></a></li>";
endwhile; endif; wp_reset_query();
echo "</ul>";
echo"<a href='".$fss_vacurl."' class='view'>".$fss_morevac."</a>";
echo $after_widget;
}
}
add_action( 'widgets_init', create_function('', 'return register_widget("FSSVacancyWidget");') );
</code></pre>
| [
{
"answer_id": 252577,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 4,
"selected": true,
"text": "<p>An error about something on <strong>line 1</strong> that is actually on a later position means that PHP doesn't recogn... | 2017/01/14 | [
"https://wordpress.stackexchange.com/questions/252532",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3782/"
] | After upgrading to php 5.6.4 my widgets file causes:
`Parse error: syntax error, unexpected 'class' (T_CLASS) in /home/path/fss-widgets.php on line 1`
I'm mystified - several hours research has yielded nothing. The problem doesn't appear to be quoting, escaping, or anything else you would expect in this situation and the code looks ok to me.
```
<?php
/*
Plugin Name: FSS Vacancy Widget
Plugin URI: http://www.url.com/
Description: Shows recent vacancies
Author: Name
Version: 1.0
Author URI: http://www.url.com/
*/
class FSSVacancyWidget extends WP_Widget
{
function FSSVacancyWidget()
{
$widget_ops = array('classname' => 'FSSVacancyWidget', 'description' => 'Displays Recent FSS Jobs on the homepage and all other pages' );
$this->WP_Widget('FSSVacancyWidget', 'FSS Vacancies', $widget_ops);
}
function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = $instance['title'];
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_numposts'); ?>">Number of Posts (Default is 10): <input class="widefat" id="<?php echo $this->get_field_id('fss_numposts'); ?>" name="<?php echo $this->get_field_name('fss_numposts'); ?>" type="text" value="<?php echo attribute_escape($fss_numposts); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_vacurl'); ?>">Vacancy URL: <input class="widefat" id="<?php echo $this->get_field_id('fss_vacurl'); ?>" name="<?php echo $this->get_field_name('fss_vacurl'); ?>" type="text" value="<?php echo attribute_escape($fss_vacurl); ?>" /></label></p>
<p><label for="<?php echo $this->get_field_id('fss_morevac'); ?>">More Vacancies Title: <input class="widefat" id="<?php echo $this->get_field_id('fss_morevac'); ?>" name="<?php echo $this->get_field_name('fss_morevac'); ?>" type="text" value="<?php echo attribute_escape($fss_morevac); ?>" /></label></p>
<?php
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['fss_numposts'] = $new_instance['fss_numposts'];
$instance['fss_vacurl'] = $new_instance['fss_vacurl'];
$instance['fss_morevac'] = $new_instance['fss_morevac'];
return $instance;
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
/* User-selected settings. */
$fss_numposts = $instance['fss_numposts'];
$fss_vacurl = $instance['fss_vacurl'];
$fss_morevac = $instance['fss_morevac'];
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
if (!empty($title))
echo $before_title . $title . $after_title;;
echo "<ul class='items'>";
query_posts( array( 'showposts' => $fss_numposts ) );
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo "<li><a href='".get_permalink()."'><span class='job-title'>".get_the_title()."</span><span class='job-date'>".get_the_date('d m Y')."</span></a></li>";
endwhile; endif; wp_reset_query();
echo "</ul>";
echo"<a href='".$fss_vacurl."' class='view'>".$fss_morevac."</a>";
echo $after_widget;
}
}
add_action( 'widgets_init', create_function('', 'return register_widget("FSSVacancyWidget");') );
``` | An error about something on **line 1** that is actually on a later position means that PHP doesn't recognize your line endings.
There are three ways to encode a line ending, and PHP understands only two of them:
1. LF, or `\n`, Line Feed, [U+000A](http://www.fileformat.info/info/unicode/char/000A/index.htm)
2. CR, or `\r`, Carriage Return, [U+000D](http://www.fileformat.info/info/unicode/char/000D/index.htm)
3. CRLF, or `\r\n`, the combination of the first and the second
LF is the default on systems like UNIX, Linux, and Mac OS X (since 2001).
CRLF is the default in Windows, inherited from [CP/M](https://en.wikipedia.org/wiki/CP/M). Just LF works on Windows too nowadays, there is no need to use CRLF anymore.
CR was the default in [Classic Mac OS](https://en.wikipedia.org/wiki/Classic_Mac_OS) until 2001.
PHP doesn't understand 2., CR only, which is understandable, because no one is using that anymore. Well, almost no one. There are still some editors out there that not only allow that obsolete line ending encoding, they don't even warn their users when they are using it.
Set your editor to use LF only, and you are safe. Unfortunately, the [WordPress Coding Standards](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/) are silent about this. |
252,559 | <p>I have image file stored inside theme directory called site.</p>
<p>Now in my home page using wordpress page editor I have put the following code but it didn't display image, seems location is wrong.</p>
<pre><code><img src="site/images/footLogo.png" style="padding: 0px!important; color:white">
</code></pre>
<p>let me know what issue?</p>
| [
{
"answer_id": 252561,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You'll have to copy the full path to the image like so:<br>\n<code>http://www.your-site-name.extension/wp... | 2017/01/15 | [
"https://wordpress.stackexchange.com/questions/252559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110935/"
] | I have image file stored inside theme directory called site.
Now in my home page using wordpress page editor I have put the following code but it didn't display image, seems location is wrong.
```
<img src="site/images/footLogo.png" style="padding: 0px!important; color:white">
```
let me know what issue? | You can define constant in theme function file as:
```
if( !defined(THEME_IMG_PATH)){
define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/site/images' );
}
```
and then you can use img tag as
```
<img src="<?php echo THEME_IMG_PATH; ?>/footLogo.png" style="padding: 0px!important; color:white">
``` |
252,595 | <p>Here's the codes i used to display the posts of my custom post "episode"</p>
<pre><code><?php
if( is_home() ){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array('post_type'=>array('episodes',),'paged'=>$paged ) ); } ?>
<?php if (have_posts()) : ?>
<?php post_movies_true(); ?>
<?php while (have_posts()) : the_post(); {?>
</code></pre>
<p>How can i add post_per_page there to limit the posts of my custom post?</p>
<p>PS: i dont really know how to code im just trying to do some custom modification with the theme i bought. I would really appreciate any help. Thanks.</p>
| [
{
"answer_id": 252561,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You'll have to copy the full path to the image like so:<br>\n<code>http://www.your-site-name.extension/wp... | 2017/01/15 | [
"https://wordpress.stackexchange.com/questions/252595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110405/"
] | Here's the codes i used to display the posts of my custom post "episode"
```
<?php
if( is_home() ){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array('post_type'=>array('episodes',),'paged'=>$paged ) ); } ?>
<?php if (have_posts()) : ?>
<?php post_movies_true(); ?>
<?php while (have_posts()) : the_post(); {?>
```
How can i add post\_per\_page there to limit the posts of my custom post?
PS: i dont really know how to code im just trying to do some custom modification with the theme i bought. I would really appreciate any help. Thanks. | You can define constant in theme function file as:
```
if( !defined(THEME_IMG_PATH)){
define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/site/images' );
}
```
and then you can use img tag as
```
<img src="<?php echo THEME_IMG_PATH; ?>/footLogo.png" style="padding: 0px!important; color:white">
``` |
252,609 | <p>i want show last 3 days posts Randomly.
how can i edit this code?</p>
<pre><code><?php
$randompost = array(
'numberposts' => 2,
'type' => 'news',
'orderby' => 'rand',
'year' => date( 'Y' ),
'week' => date( 'W' ),
);
$rand_posts = get_posts( $randompost );
foreach( $rand_posts as $post ) : ?>
<?php endforeach; ?>
</code></pre>
| [
{
"answer_id": 252621,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the code below:</p>\n\n<pre><code>$today = getdate();\n$randompost = array(\n 'date_query'... | 2017/01/15 | [
"https://wordpress.stackexchange.com/questions/252609",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107899/"
] | i want show last 3 days posts Randomly.
how can i edit this code?
```
<?php
$randompost = array(
'numberposts' => 2,
'type' => 'news',
'orderby' => 'rand',
'year' => date( 'Y' ),
'week' => date( 'W' ),
);
$rand_posts = get_posts( $randompost );
foreach( $rand_posts as $post ) : ?>
<?php endforeach; ?>
``` | You can use this code for show last 3 days post. Best of luck...
```
$args = array(
'post_status' => 'publish',
'type' => 'news',
'posts_per_page' => 2,
'order' => 'rand',
'date_query' => array(
array(
'after' => '3 days ago'
)
)
);
``` |
252,620 | <p>As in wordpress multi site, wordpress removed "Ping List Text Area" from Setting->Writing added Text Field in Network-Admin->All-Sites->Edit->Settings, I'm not able to understand that How we should add Ping List Url in text field.
Eg.:
http ://xyz [dot] com/rpc2 , http ://xyz1 [dot] com/rpc2
or
http ://xyz [dot] com/rpc2 http ://xyz1[dot]com/rpc2</p>
<p>Please explain that what we should use between two url, comma or space?</p>
| [
{
"answer_id": 252621,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the code below:</p>\n\n<pre><code>$today = getdate();\n$randompost = array(\n 'date_query'... | 2017/01/15 | [
"https://wordpress.stackexchange.com/questions/252620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110962/"
] | As in wordpress multi site, wordpress removed "Ping List Text Area" from Setting->Writing added Text Field in Network-Admin->All-Sites->Edit->Settings, I'm not able to understand that How we should add Ping List Url in text field.
Eg.:
http ://xyz [dot] com/rpc2 , http ://xyz1 [dot] com/rpc2
or
http ://xyz [dot] com/rpc2 http ://xyz1[dot]com/rpc2
Please explain that what we should use between two url, comma or space? | You can use this code for show last 3 days post. Best of luck...
```
$args = array(
'post_status' => 'publish',
'type' => 'news',
'posts_per_page' => 2,
'order' => 'rand',
'date_query' => array(
array(
'after' => '3 days ago'
)
)
);
``` |
252,622 | <p>I'm using the plugin 'Ninja From' and I'm trying to stop it from loading a CSS file in the header.</p>
<p>The CSS file:</p>
<pre><code><link rel='stylesheet' id='nf-display-css' href='http://example.com/wp-content/plugins/ninja-forms/assets/css/display-structure.css?ver=4.7.1' type='text/css' media='all' />
</code></pre>
<p>My code:</p>
<pre><code>function remove_css_ninja_form(){
wp_dequeue_style('nf-display-css');
wp_deregister_style('nf-display-css');
}
add_action( 'wp_enqueue_scripts', 'remove_css_ninja_form', 99999 );
add_action( 'wp_print_styles', 'remove_css_ninja_form', 99999 );
add_action( 'wp_head', 'remove_css_ninja_form', 9999 );
</code></pre>
<p>It is not working.</p>
| [
{
"answer_id": 252623,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>In WordPress priority <code>$arg</code>, <em>Lower numbers correspond with earlier execution, and functi... | 2017/01/15 | [
"https://wordpress.stackexchange.com/questions/252622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110964/"
] | I'm using the plugin 'Ninja From' and I'm trying to stop it from loading a CSS file in the header.
The CSS file:
```
<link rel='stylesheet' id='nf-display-css' href='http://example.com/wp-content/plugins/ninja-forms/assets/css/display-structure.css?ver=4.7.1' type='text/css' media='all' />
```
My code:
```
function remove_css_ninja_form(){
wp_dequeue_style('nf-display-css');
wp_deregister_style('nf-display-css');
}
add_action( 'wp_enqueue_scripts', 'remove_css_ninja_form', 99999 );
add_action( 'wp_print_styles', 'remove_css_ninja_form', 99999 );
add_action( 'wp_head', 'remove_css_ninja_form', 9999 );
```
It is not working. | Extract the ninja form plugin's files to a folder, and use a text editor such as Notepad++ to search within the files of the plugin and find either one of these phrases:
```
`wp_enqueue_style` OR `css_ninja_form`
```
You will end up with at least 1 result, which will be similar to :
```
add_action( 'wp_enqueue_scripts', 'css_ninja_form', xyz );
```
Which xyz is the priority the author of the plugin used to enqueue it. Now, you can directly remove the line from the result page (not recommended) or you can use the xyz priority to dequeue the script in your function.php. |
252,640 | <p>I have implemented AAPL on a new website which loads in Wordpress pages using AJAX.</p>
<p>Problem: For some unknown reason, css styles which are supposed to be loaded via enqueue are not being loaded.</p>
<p>If I click a page, some effects and transitions don't load - when checking the element, the css isn't visible. I then click "reload" which loads the page normally, and everything works perfectly.</p>
<p>Site: <a href="http://murrayfredericks.oleymedia.com/projects/" rel="nofollow noreferrer">http://murrayfredericks.oleymedia.com/projects/</a></p>
<p>Click "Greenlands" -> "Information" - you can see it loads the font in Times New Roman instead of the styles from bootstrap.css.
Reload the page and voila - problem resolved - bootstrap.css is loaded?</p>
<p>E.g.
When I click the "Information" page and view the source for the first column element:</p>
<pre><code><div class="wpb_column vc_column_container vc_col-sm-3 catlistli visible">
</code></pre>
<p>This is what I see:</p>
<p><a href="https://i.stack.imgur.com/uPWAI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uPWAI.png" alt="enter image description here"></a></p>
<p>Then, when I reload, I view the exact same element and this is what I see:</p>
<p><a href="https://i.stack.imgur.com/wzUYg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wzUYg.png" alt="enter image description here"></a></p>
<p>NOTE: See now that the js_composer.min.css is now being applied to the same element and is formatting it properly so that it looks how it should look.</p>
<p>It seems to never be the /child-theme/style.css that isn't applied - it's only ever js_composer.css or bootstrap.css</p>
| [
{
"answer_id": 252623,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>In WordPress priority <code>$arg</code>, <em>Lower numbers correspond with earlier execution, and functi... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10368/"
] | I have implemented AAPL on a new website which loads in Wordpress pages using AJAX.
Problem: For some unknown reason, css styles which are supposed to be loaded via enqueue are not being loaded.
If I click a page, some effects and transitions don't load - when checking the element, the css isn't visible. I then click "reload" which loads the page normally, and everything works perfectly.
Site: <http://murrayfredericks.oleymedia.com/projects/>
Click "Greenlands" -> "Information" - you can see it loads the font in Times New Roman instead of the styles from bootstrap.css.
Reload the page and voila - problem resolved - bootstrap.css is loaded?
E.g.
When I click the "Information" page and view the source for the first column element:
```
<div class="wpb_column vc_column_container vc_col-sm-3 catlistli visible">
```
This is what I see:
[](https://i.stack.imgur.com/uPWAI.png)
Then, when I reload, I view the exact same element and this is what I see:
[](https://i.stack.imgur.com/wzUYg.png)
NOTE: See now that the js\_composer.min.css is now being applied to the same element and is formatting it properly so that it looks how it should look.
It seems to never be the /child-theme/style.css that isn't applied - it's only ever js\_composer.css or bootstrap.css | Extract the ninja form plugin's files to a folder, and use a text editor such as Notepad++ to search within the files of the plugin and find either one of these phrases:
```
`wp_enqueue_style` OR `css_ninja_form`
```
You will end up with at least 1 result, which will be similar to :
```
add_action( 'wp_enqueue_scripts', 'css_ninja_form', xyz );
```
Which xyz is the priority the author of the plugin used to enqueue it. Now, you can directly remove the line from the result page (not recommended) or you can use the xyz priority to dequeue the script in your function.php. |
252,645 | <p>I am new in wordpress, and I want to change a word in theme,for example in one of pages I have "view all" word, I want to change it to "see all"
How can i do this?</p>
| [
{
"answer_id": 252646,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 3,
"selected": true,
"text": "<p>Some would say it is hard to answer based on the few information you provided.</p>\n\n<p>However, the answer ma... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110983/"
] | I am new in wordpress, and I want to change a word in theme,for example in one of pages I have "view all" word, I want to change it to "see all"
How can i do this? | Some would say it is hard to answer based on the few information you provided.
However, the answer may be general enough to cover many more problems similar to your case.
First I would install this [plugin](https://wordpress.org/plugins/show-current-template/).
Check the screenshots section for more info:
<https://wordpress.org/plugins/show-current-template/screenshots/>
It will provide you the list of files in use. This may be handy when you search where to edit your theme.
Editing themes directly is not recommended, but if you don't care and just need to make it work than it is OK.
Normally you would create the child theme, or work on your translation for the theme.
You can use this kind of hooking to replace some string with another string for the whole theme if you add this to the `functions.php` file
```
function _20170116_replace_text ( $text ) {
// possible add the condition when ...
if ($text == 'View All'){$text = 'See All';}
return $text;
}
add_filter( 'gettext', '_20170116_replace_text' );
```
Check this and let me know if this works. With the `show-current-template` you can thinker the condition when to replace this text.
The condition you need to add to `20170116_replace_text` may look like this:
```
if (in_array( $GLOBALS['pagenow'], array( 'your-page.php' ) )) {
}
``` |
252,658 | <p>Need to switch theme when accessed from sub domain. There is nothing installed in the sub domain. I have setup a subdomain as a CNAME pointing to the original domain. Then, detect whether or not the visitor is on the subdomain by looking at $_SERVER[‘SERVER_NAME’]. Went through various sources and have found out this code but could not make this working.</p>
<p>Note: I am a newbie</p>
<pre><code>// regular site url
$my_url = 'http://example.com';
// subdomain you want a different theme on
$my_sub_url = 'http://sub.example.com';
// subdomain prefix, used to test whether primary or subdomain
$my_prefix = 'sub.';
// folder name of theme to use instead on subdomain
$my_theme_name = 'my_mobile_theme';
add_filter( 'template' , 'my_change_theme' );
add_filter( 'option_template' , 'my_change_theme' );
add_filter( 'option_stylesheet' , 'my_change_theme' );
// these 2 actions rewrite all urls in the body
// from main to sub domain
add_action( 'wp_head' , 'my_buffer_start' );
add_action( 'wp_footer' , 'my_buffer_end' );
// TRUE, if this is the subdomain, false otherwise
public function my_is_subdomain() {
global $my_prefix;
if( strpos( $_SERVER['SERVER_NAME'], $my_prefix ) !== FALSE ) {
return TRUE;
}
return FALSE;
}
// if this is the subdomain, return new theme
// otherwise, return original theme
public function my_change_theme( $theme ) {
global $my_theme_name;
if( my_is_subdomain() ) {
return $my_theme_name;
}
return $theme;
}
public function my_buffer_start() {
ob_start('my_buffer_cb');
}
public function my_buffer_end() {
ob_end_flush();
}
// replace primary url with subdomain url in body
// so that all links keep user on the subdomain
public function my_buffer_cb( $buffer ) {
global $my__url, $my_sub_url;
if( ! my_is_subdomain() ) {
return $buffer;
}
// replace main domain with sub domain
$buffer = str_replace( $my_url, $my_sub_url, $buffer);
// !!! NOTE - you may not want to replace EVERY instance
// for example, you may want to keep social media urls
// intact, or rel="canonical", or links specifically
// designed to switch between the primary and subdomain
return $buffer;
}
</code></pre>
| [
{
"answer_id": 252665,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress supports only one theme on site. Actions like shown will cause a adverse effects.\nInstead, ... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252658",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111003/"
] | Need to switch theme when accessed from sub domain. There is nothing installed in the sub domain. I have setup a subdomain as a CNAME pointing to the original domain. Then, detect whether or not the visitor is on the subdomain by looking at $\_SERVER[‘SERVER\_NAME’]. Went through various sources and have found out this code but could not make this working.
Note: I am a newbie
```
// regular site url
$my_url = 'http://example.com';
// subdomain you want a different theme on
$my_sub_url = 'http://sub.example.com';
// subdomain prefix, used to test whether primary or subdomain
$my_prefix = 'sub.';
// folder name of theme to use instead on subdomain
$my_theme_name = 'my_mobile_theme';
add_filter( 'template' , 'my_change_theme' );
add_filter( 'option_template' , 'my_change_theme' );
add_filter( 'option_stylesheet' , 'my_change_theme' );
// these 2 actions rewrite all urls in the body
// from main to sub domain
add_action( 'wp_head' , 'my_buffer_start' );
add_action( 'wp_footer' , 'my_buffer_end' );
// TRUE, if this is the subdomain, false otherwise
public function my_is_subdomain() {
global $my_prefix;
if( strpos( $_SERVER['SERVER_NAME'], $my_prefix ) !== FALSE ) {
return TRUE;
}
return FALSE;
}
// if this is the subdomain, return new theme
// otherwise, return original theme
public function my_change_theme( $theme ) {
global $my_theme_name;
if( my_is_subdomain() ) {
return $my_theme_name;
}
return $theme;
}
public function my_buffer_start() {
ob_start('my_buffer_cb');
}
public function my_buffer_end() {
ob_end_flush();
}
// replace primary url with subdomain url in body
// so that all links keep user on the subdomain
public function my_buffer_cb( $buffer ) {
global $my__url, $my_sub_url;
if( ! my_is_subdomain() ) {
return $buffer;
}
// replace main domain with sub domain
$buffer = str_replace( $my_url, $my_sub_url, $buffer);
// !!! NOTE - you may not want to replace EVERY instance
// for example, you may want to keep social media urls
// intact, or rel="canonical", or links specifically
// designed to switch between the primary and subdomain
return $buffer;
}
``` | WordPress supports only one theme on site. Actions like shown will cause a adverse effects.
Instead, you should use WordPress Multisite, which allows to use different themes on subdomains. This is the way recommended by the WordPress team.
There is solution for WooCommerce on WordPress Multisite: [WooCommerce Multistore plugin:](https://woomultistore.com) It is quite expensive ($200), but struggling with unsupported features in WordPress can cost much more. |
252,680 | <p><strong>TL;DR</strong> - Why is my user account not logged in during an AJAX request which is made inside wp-admin?</p>
<hr>
<p>I have the following setup:</p>
<pre><code><?php
add_action('wp_ajax_foobar_action', 'foobar_action');
add_action('wp_ajax_nopriv_foobar_action', 'foobar_action');
function foobar_action() {
check_ajax_referrer();
wp_send_json((object) ['msg' => 'hello world']);
}
add_action('admin_print_scripts', function () {
printf('<script type="text/javascript">window.custom_nonce = "%s";</script>', wp_create_nonce());
});
</code></pre>
<p>And in JS:</p>
<pre><code>var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce
}).then(function (res) {
msg = res.json().msg;
});
</code></pre>
<p>This is all run in wp-admin. The issue is that the wp-admin page/JS script itself is loaded as a logged in user, but the AJAX request that ends up into admin-ajax.php is done as a logged out guest user. This leads to the issue of wp-admin using <code>nopriv</code> and <code>check_ajax_referrer</code> failing 100% of the time.</p>
<p>Why does wp-admin make AJAX requests as a guest instead of the logged in user?</p>
<p>Currently, the AJAX endpoint returns <code>403</code> status with <code>-1</code> content, as it should in case there is a nonce mismatch. If I comment out the <code>check_ajax_referrer()</code> call then the AJAX request runs through successfully. After some furious <code>console.log</code>ging I've determined that the nonce values match in the JS fetch call and the AJAX endpoint that receives it (which means the nonce is properly transferred, but a wrong guest nonce is generated during the AJAX endpoint execution.</p>
<p>If I remove the <code>wp_ajax_nopriv_foobar_action</code> then WordPress doesn't find the auth-enabled AJAX action because there seemingly is no logged in user available (results in status <code>200</code> and body <code>0</code>).</p>
<p>Steps I've attempted to fix the issue:</p>
<ul>
<li>Logged out and in again, cleared caches/cookies, used incognito windows,</li>
<li>Restarted PHP-FPM, Nginx, object cache backends, MariaDB,</li>
<li>Disabled all plugins that are not required for operation,</li>
<li>Moved the AJAX hooking code around in my plugin code, all the way to the plugin root file (e.g. <code>myplugin/myplugin.php</code>),</li>
<li>Used GET instead of POST.</li>
</ul>
| [
{
"answer_id": 252683,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think problem could be due to the consequence: </p>\n\n<p>in HTML source, firstly, this should be outputed:... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34299/"
] | **TL;DR** - Why is my user account not logged in during an AJAX request which is made inside wp-admin?
---
I have the following setup:
```
<?php
add_action('wp_ajax_foobar_action', 'foobar_action');
add_action('wp_ajax_nopriv_foobar_action', 'foobar_action');
function foobar_action() {
check_ajax_referrer();
wp_send_json((object) ['msg' => 'hello world']);
}
add_action('admin_print_scripts', function () {
printf('<script type="text/javascript">window.custom_nonce = "%s";</script>', wp_create_nonce());
});
```
And in JS:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce
}).then(function (res) {
msg = res.json().msg;
});
```
This is all run in wp-admin. The issue is that the wp-admin page/JS script itself is loaded as a logged in user, but the AJAX request that ends up into admin-ajax.php is done as a logged out guest user. This leads to the issue of wp-admin using `nopriv` and `check_ajax_referrer` failing 100% of the time.
Why does wp-admin make AJAX requests as a guest instead of the logged in user?
Currently, the AJAX endpoint returns `403` status with `-1` content, as it should in case there is a nonce mismatch. If I comment out the `check_ajax_referrer()` call then the AJAX request runs through successfully. After some furious `console.log`ging I've determined that the nonce values match in the JS fetch call and the AJAX endpoint that receives it (which means the nonce is properly transferred, but a wrong guest nonce is generated during the AJAX endpoint execution.
If I remove the `wp_ajax_nopriv_foobar_action` then WordPress doesn't find the auth-enabled AJAX action because there seemingly is no logged in user available (results in status `200` and body `0`).
Steps I've attempted to fix the issue:
* Logged out and in again, cleared caches/cookies, used incognito windows,
* Restarted PHP-FPM, Nginx, object cache backends, MariaDB,
* Disabled all plugins that are not required for operation,
* Moved the AJAX hooking code around in my plugin code, all the way to the plugin root file (e.g. `myplugin/myplugin.php`),
* Used GET instead of POST. | After some fiddling and sparring with @t-todua I found the issue:
With the Fetch API `fetch` call you must manually set to send cookies with a request. After setting the `credentials` option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,
credentials: 'same-origin'
}).then(function (res) {
msg = res.json().msg;
});
``` |
252,689 | <p>I have written following js code</p>
<pre><code>jQuery(".selectbox").change(function(){
var id = this.id;
var key_id=id;
var selectname='';
jQuery.post(
// see tip #1 for how we declare global javascript variables
MyAjax.ajaxurl,
{
// here we declare the parameters to send along with the request
// this means the following action hooks will be fired:
// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
action : 'get-mata-value',
// other parameters can be added along with "action"
prev_metakey : jQuery(this).val(),
metakey: key_id
},
function( result ) {
if(result['success'] != false)
{
jQuery.each(result,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
}
);
</code></pre>
<p>});</p>
<p>and function is:</p>
<pre><code>wp_localize_script( 'script', 'MyAjax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/vehicle_parts.js', array ( 'jquery' ), 1.1, true);
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$prev_value=$_POST["prev_metakey"];
$result=array();
$result=$wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = '$key'");
return($result);
}
</code></pre>
<p>when I change select box the function is not being called.</p>
| [
{
"answer_id": 252683,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think problem could be due to the consequence: </p>\n\n<p>in HTML source, firstly, this should be outputed:... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252689",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95126/"
] | I have written following js code
```
jQuery(".selectbox").change(function(){
var id = this.id;
var key_id=id;
var selectname='';
jQuery.post(
// see tip #1 for how we declare global javascript variables
MyAjax.ajaxurl,
{
// here we declare the parameters to send along with the request
// this means the following action hooks will be fired:
// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
action : 'get-mata-value',
// other parameters can be added along with "action"
prev_metakey : jQuery(this).val(),
metakey: key_id
},
function( result ) {
if(result['success'] != false)
{
jQuery.each(result,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
}
);
```
});
and function is:
```
wp_localize_script( 'script', 'MyAjax',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
)
);
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/vehicle_parts.js', array ( 'jquery' ), 1.1, true);
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$prev_value=$_POST["prev_metakey"];
$result=array();
$result=$wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = '$key'");
return($result);
}
```
when I change select box the function is not being called. | After some fiddling and sparring with @t-todua I found the issue:
With the Fetch API `fetch` call you must manually set to send cookies with a request. After setting the `credentials` option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,
credentials: 'same-origin'
}).then(function (res) {
msg = res.json().msg;
});
``` |
252,700 | <p>Sorry if it's a duplicate question,
I just want to change a little the WordPress core function <code>get_header()</code> with new function <code>new_get_header()</code>.</p>
<pre><code>function new_get_header() {
// new header fragments;
}
</code></pre>
<p><strong>Is this possible?</strong></p>
<pre><code>add_filter( 'get_header', 'new_get_header' );
</code></pre>
<p><strong>Or should I use:</strong></p>
<pre><code>add_action( 'init', 'new_get_header' );
</code></pre>
<p>And call it as a function instead of original.</p>
<pre><code>new_get_header();
// Content
// Footer
</code></pre>
| [
{
"answer_id": 252683,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think problem could be due to the consequence: </p>\n\n<p>in HTML source, firstly, this should be outputed:... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252700",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101492/"
] | Sorry if it's a duplicate question,
I just want to change a little the WordPress core function `get_header()` with new function `new_get_header()`.
```
function new_get_header() {
// new header fragments;
}
```
**Is this possible?**
```
add_filter( 'get_header', 'new_get_header' );
```
**Or should I use:**
```
add_action( 'init', 'new_get_header' );
```
And call it as a function instead of original.
```
new_get_header();
// Content
// Footer
``` | After some fiddling and sparring with @t-todua I found the issue:
With the Fetch API `fetch` call you must manually set to send cookies with a request. After setting the `credentials` option properly the cookies were sent and the AJAX endpoint recognized the current user. So the JS becomes:
```
var msg = '';
// I'm using the whatwg-fetch polyfill and a polyfill for Promises.
fetch(ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'action=foobar_action&_wpnonce=' + window.custom_nonce,
credentials: 'same-origin'
}).then(function (res) {
msg = res.json().msg;
});
``` |
252,709 | <p>I am trying to figure out if it is possible to add elements to the widgetpage in WordPress' dashboard without editing the widgets.php core file. Is there a WordPress function or something else (maybe even a jQuery solution) that will get this done? </p>
<p>If I google this the only results are about widget area's but I just need to add an image (like really an img element, not a widget) to the widget page.</p>
<p>Is there anyone that knows if this is possible and give me some hint/help.</p>
| [
{
"answer_id": 252721,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 0,
"selected": false,
"text": "<p>There is few <code>action</code> hooks in <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111030/"
] | I am trying to figure out if it is possible to add elements to the widgetpage in WordPress' dashboard without editing the widgets.php core file. Is there a WordPress function or something else (maybe even a jQuery solution) that will get this done?
If I google this the only results are about widget area's but I just need to add an image (like really an img element, not a widget) to the widget page.
Is there anyone that knows if this is possible and give me some hint/help. | You can use @kudratullah's suggestion to hook into the widgets page. The downside is that this allows insertion of a piece of html only in one specific place. If that location is ok, use that solution.
Otherwise, there are two other possibilities.
The first is to use jquery. Examine the source to identify the html element where you want to add your image (let's say #wrap). Then [append](http://api.jquery.com/append/) the node like this:
```
$( "#wrap" ).append( "<img src='....' />" );
```
The second is to use the css after pseudoclass like this:
```
#wrap:after {content:url('/path/to/mypic.jpg');}
```
Both style and script files need to be [enqueued to the admin](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts). |
252,715 | <p>I have created the following "plugin" following the codex but it doesn't seem to work. It is supposed to add 100 points to user meta everytime he/she posts a new blog post.</p>
<p>Could you please let me know what is wrong with it...</p>
<pre><code>function post_published_add_points( $ID, $post ) {
$author = $post->post_author; /* Post author ID. */
add_user_meta( $author, 'Points', '100');
}
add_action( 'publish_post', 'post_published_add_points', 10, 2 );
</code></pre>
<p>Thanks!
Dragos</p>
| [
{
"answer_id": 252721,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 0,
"selected": false,
"text": "<p>There is few <code>action</code> hooks in <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110131/"
] | I have created the following "plugin" following the codex but it doesn't seem to work. It is supposed to add 100 points to user meta everytime he/she posts a new blog post.
Could you please let me know what is wrong with it...
```
function post_published_add_points( $ID, $post ) {
$author = $post->post_author; /* Post author ID. */
add_user_meta( $author, 'Points', '100');
}
add_action( 'publish_post', 'post_published_add_points', 10, 2 );
```
Thanks!
Dragos | You can use @kudratullah's suggestion to hook into the widgets page. The downside is that this allows insertion of a piece of html only in one specific place. If that location is ok, use that solution.
Otherwise, there are two other possibilities.
The first is to use jquery. Examine the source to identify the html element where you want to add your image (let's say #wrap). Then [append](http://api.jquery.com/append/) the node like this:
```
$( "#wrap" ).append( "<img src='....' />" );
```
The second is to use the css after pseudoclass like this:
```
#wrap:after {content:url('/path/to/mypic.jpg');}
```
Both style and script files need to be [enqueued to the admin](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts). |
252,730 | <p>I need to set 1 cookie, saving a data sent from a form.</p>
<p>I see that I have to hook my setcookie() to the 'init'. That's OK.</p>
<pre><code>add_action( 'init', 'cookie_function');
</code></pre>
<p>My 'cookie_function' will have $cookieName, $cookieValue, $time, COOKIEPATH, COOKIEDOMAIN.</p>
<p>If I need something like setcookie('test', $_POST['test']), what do I call:</p>
<pre><code>cookie_function() //and where do I pass parameters?
</code></pre>
<p>or</p>
<pre><code>setcookie() //and this function will be related to my cookie_function()?
</code></pre>
| [
{
"answer_id": 252734,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>You use setcookie() like any other function, with parameters as described in the Codex. </p>\n\n<p>How you... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111037/"
] | I need to set 1 cookie, saving a data sent from a form.
I see that I have to hook my setcookie() to the 'init'. That's OK.
```
add_action( 'init', 'cookie_function');
```
My 'cookie\_function' will have $cookieName, $cookieValue, $time, COOKIEPATH, COOKIEDOMAIN.
If I need something like setcookie('test', $\_POST['test']), what do I call:
```
cookie_function() //and where do I pass parameters?
```
or
```
setcookie() //and this function will be related to my cookie_function()?
``` | You use setcookie() like any other function, with parameters as described in the Codex.
How you would use it in a form would usually depend on how and when the $\_COOKIE variable needs to be made accessible.
One common method, if you want a change in the DOM both to register immediately and to persist, is to use a Javascript/jQuery function whose effect is duplicated in the PHP functions that will draw upon $\_COOKIE variables. The cookie will also typically be set or updated in the same script, commonly with the aid of jquery-cookie or js-cookie. |
252,740 | <p>I'm building currently a website on WordPress. The site has a custom post type. I have a customized search form, which selects entries from custom post type. Entries are being selected and sorted as they are supposed to, however on my search result page (job-search.php) I need a pagination, and it's not working, although same codes works fine on other pages. I see page number changing in browser's search bar, but I always see entries from first page.</p>
<p>Code for search form and query for custom post type with specified selections and filtering (inside job-search.php):</p>
<pre><code><?php
/*
* Template Name:job-search
*/
get_header();?>
<div>
<form method="get" action="<?php echo site_url('/'); ?>/job-search" >
<input type="search" name="job-name" placeholder="Job..." />
<input type="search" name="town-name" placeholder="Town..." />
<select type="search" name="date">
<option value="DESC">Datum absteigend</option>
<option value="ASC">Datum aufsteigend</option>
</select>
<div>
<input type="checkbox" name="cat[]" value="IT, Telekommunikation" />IT, Telekommunikation
<input type="checkbox" name="cat[]" value="Ingenieur, Technik" />Ingenieur, Technik
<input type="checkbox" name="cat[]" value="Handwerk, Gewerbe" />Handwerk, Gewerbe
</div>
<input type="submit" value="Search">
</form>
</div>
<?php
$jobName = $_GET['job-name'];
$jobTown = $_GET['town-name'];
$jobDate = $_GET['date'];
if($_GET['cat'] && !empty($_GET['cat'])){
$jobCat = $_GET['cat'];
}
else{
$jobCat = array('Vertrieb, Verkauf', 'IT, Telekommunikation', 'Ingenieur, Technik', 'Personalwesen', 'Bildung, Soziales', 'Einkauf, Logistik', 'Handwerk, Gewerbe', 'Führungskräfte', 'Marketing, PR', 'Medizin, Pflege', 'Finanzen, Steuern, Recht', 'Kaufmännische Berufe', 'Luft- und Raumfahrt, Reise', 'Ausbildung', '');
}
?>
<h1 style="font-size:1.5em; font-weight:bold; border-bottom:2px solid green; color:green; margin-bottom:20px;">wp_query_search results</h1>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$q1 = array(
'post_type' => 'jobs',
's' => $jobName,
'posts_per_page' => 10,
'paged' => $paged,
'meta_key' => 'date',
'orderby' => 'meta_value',
'order' => $jobDate,
'meta_query' => array (
'relation' => 'AND',
array(
'key' => 'town',
'value' => $jobTown,
'compare' => 'LIKE'
),
array(
'relation' => 'OR',
array(
'key' => 'cat_1',
'value' => $jobCat
),
array(
'key' => 'cat_2',
'value' => $jobCat
)
)
)
);
$query = new WP_Query($q1);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();?>
<h2 style="color:brown; font-weight:bold; border-bottom:1px dotted brown;"><?php the_field('title'); ?></h2>
<h3><?php the_field('town'); ?></h3>
<h4><?php the_field('cat_1'); ?> | <?php the_field('cat_2'); ?></h4>
<h5><?php the_field('date'); ?></h5>
<?php endwhile;
if (function_exists(search_pagination)) {
search_pagination($query->max_num_pages,"",$paged);
}
endif; wp_reset_query(); ?>
</div>
<?php get_footer(); ?>
</code></pre>
<p>Code for Pagination (inside functions.php):</p>
<pre><code>function search_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
$paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
//global $wp_query;
//$numpages = $wp_query->max_num_pages;
$numpages = $query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('&laquo;'),
'next_text' => __('&raquo;'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo $paginate_links;
echo "</nav>";
}
}
</code></pre>
<p>I truly need help and advices. Thanks a lot in advance!</p>
| [
{
"answer_id": 252742,
"author": "socki03",
"author_id": 43511,
"author_profile": "https://wordpress.stackexchange.com/users/43511",
"pm_score": -1,
"selected": false,
"text": "<p>Everything looks like things I've used in a similar fashion. The only thing, is, I believe the <code>functi... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105223/"
] | I'm building currently a website on WordPress. The site has a custom post type. I have a customized search form, which selects entries from custom post type. Entries are being selected and sorted as they are supposed to, however on my search result page (job-search.php) I need a pagination, and it's not working, although same codes works fine on other pages. I see page number changing in browser's search bar, but I always see entries from first page.
Code for search form and query for custom post type with specified selections and filtering (inside job-search.php):
```
<?php
/*
* Template Name:job-search
*/
get_header();?>
<div>
<form method="get" action="<?php echo site_url('/'); ?>/job-search" >
<input type="search" name="job-name" placeholder="Job..." />
<input type="search" name="town-name" placeholder="Town..." />
<select type="search" name="date">
<option value="DESC">Datum absteigend</option>
<option value="ASC">Datum aufsteigend</option>
</select>
<div>
<input type="checkbox" name="cat[]" value="IT, Telekommunikation" />IT, Telekommunikation
<input type="checkbox" name="cat[]" value="Ingenieur, Technik" />Ingenieur, Technik
<input type="checkbox" name="cat[]" value="Handwerk, Gewerbe" />Handwerk, Gewerbe
</div>
<input type="submit" value="Search">
</form>
</div>
<?php
$jobName = $_GET['job-name'];
$jobTown = $_GET['town-name'];
$jobDate = $_GET['date'];
if($_GET['cat'] && !empty($_GET['cat'])){
$jobCat = $_GET['cat'];
}
else{
$jobCat = array('Vertrieb, Verkauf', 'IT, Telekommunikation', 'Ingenieur, Technik', 'Personalwesen', 'Bildung, Soziales', 'Einkauf, Logistik', 'Handwerk, Gewerbe', 'Führungskräfte', 'Marketing, PR', 'Medizin, Pflege', 'Finanzen, Steuern, Recht', 'Kaufmännische Berufe', 'Luft- und Raumfahrt, Reise', 'Ausbildung', '');
}
?>
<h1 style="font-size:1.5em; font-weight:bold; border-bottom:2px solid green; color:green; margin-bottom:20px;">wp_query_search results</h1>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$q1 = array(
'post_type' => 'jobs',
's' => $jobName,
'posts_per_page' => 10,
'paged' => $paged,
'meta_key' => 'date',
'orderby' => 'meta_value',
'order' => $jobDate,
'meta_query' => array (
'relation' => 'AND',
array(
'key' => 'town',
'value' => $jobTown,
'compare' => 'LIKE'
),
array(
'relation' => 'OR',
array(
'key' => 'cat_1',
'value' => $jobCat
),
array(
'key' => 'cat_2',
'value' => $jobCat
)
)
)
);
$query = new WP_Query($q1);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();?>
<h2 style="color:brown; font-weight:bold; border-bottom:1px dotted brown;"><?php the_field('title'); ?></h2>
<h3><?php the_field('town'); ?></h3>
<h4><?php the_field('cat_1'); ?> | <?php the_field('cat_2'); ?></h4>
<h5><?php the_field('date'); ?></h5>
<?php endwhile;
if (function_exists(search_pagination)) {
search_pagination($query->max_num_pages,"",$paged);
}
endif; wp_reset_query(); ?>
</div>
<?php get_footer(); ?>
```
Code for Pagination (inside functions.php):
```
function search_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
$paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
//global $wp_query;
//$numpages = $wp_query->max_num_pages;
$numpages = $query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo $paginate_links;
echo "</nav>";
}
}
```
I truly need help and advices. Thanks a lot in advance! | From your job-search.php replace `'posts_per_page' => 10,` to `'posts_per_page' => 3,`
and Simply add this following code in your search page, i mean where you are searching the posts.
```
the_posts_pagination( array( 'mid_size' => 2 ) );
``` |
252,743 | <p>I have a taxonomy called "location". I'm outputting a comma separated list of these taxonomy terms for a post. This is fine, but I don't know how to split the second-to-last and last items with "and" instead of a comma. </p>
<p>Here is my code. Is there a way to do it using the counter maybe?</p>
<pre><code>$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);
for($cat_count=0; $cat_count<count($locations); $cat_count++) {
echo $locations[$cat_count]->name;
if ($cat_count<count($locations)-1){
echo ', ';
}
}
</code></pre>
<p>Note: This code is in the sidebar for a category archive template and inside a WP_Query, so it's all within the loop. The WP_Query is outputting multiple posts of a custom post type called Projects and I'm trying to list the location tax terms for each one. </p>
| [
{
"answer_id": 252746,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 3,
"selected": true,
"text": "<p>This is how your code should look like I added some comments so you will understand its simple programming not r... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22448/"
] | I have a taxonomy called "location". I'm outputting a comma separated list of these taxonomy terms for a post. This is fine, but I don't know how to split the second-to-last and last items with "and" instead of a comma.
Here is my code. Is there a way to do it using the counter maybe?
```
$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);
for($cat_count=0; $cat_count<count($locations); $cat_count++) {
echo $locations[$cat_count]->name;
if ($cat_count<count($locations)-1){
echo ', ';
}
}
```
Note: This code is in the sidebar for a category archive template and inside a WP\_Query, so it's all within the loop. The WP\_Query is outputting multiple posts of a custom post type called Projects and I'm trying to list the location tax terms for each one. | This is how your code should look like I added some comments so you will understand its simple programming not really wordpress related.
```
$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);
$total_locations = count($locations); // the total start from 1
for($i = 0; $i < $total_locations; $i++) {
echo $locations[$i]; // echo the location
if($i < $total_locations-2) { // so for comma you need to check if the for loop variable is - 2 because the loop start from 0
echo ', '; // echo comma
} elseif($i < $total_locations-1) { // and here is just -1 because you want to print it before the last one because this we use the less than sign in both of our conditions
echo ' and '; // echo and
}
}
``` |
252,760 | <p>I am trying to load more content with ajax. the script does not return anything when I am logged out.</p>
<p>this is my php code</p>
<pre><code><?php
function get_blog_items()
{
$offset = (int)intval($_POST['offset']);
$args = array(
'posts_per_page' => 4,
'post_type' => 'post',
'offset' => $offset
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/list', 'blog' );
endwhile;
endif;
wp_reset_postdata();
}
function add_ajax_actions() {
add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );
}
add_action( 'admin_init', 'add_ajax_actions' );
</code></pre>
<p>And my javascript</p>
<pre><code>$(document).ready(function($) {
var loadbuttonBlogItems = $('#loadmore-blog-items');
loadbuttonBlogItems.on('click', function() {
$(this).addClass('loading');
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
dataType: 'html',
data: {
action: 'get_blog_items',
offset: $('body > div.page-wrap > section.blog-listing > ul').children().length
},
})
.done(function(data) {
console.log(data);
$('.blog-listing ul').append($.parseHTML(data))
})
.fail(function() {
console.log("error occured while loading more blog items");
})
.always(function() {
console.log("ajax call finished");
$(loadbuttonBlogItems).removeClass('loading');
});
})
});
</code></pre>
| [
{
"answer_id": 252761,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function add_ajax_actions() {\n add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );\... | 2017/01/16 | [
"https://wordpress.stackexchange.com/questions/252760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107702/"
] | I am trying to load more content with ajax. the script does not return anything when I am logged out.
this is my php code
```
<?php
function get_blog_items()
{
$offset = (int)intval($_POST['offset']);
$args = array(
'posts_per_page' => 4,
'post_type' => 'post',
'offset' => $offset
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'template-parts/list', 'blog' );
endwhile;
endif;
wp_reset_postdata();
}
function add_ajax_actions() {
add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );
}
add_action( 'admin_init', 'add_ajax_actions' );
```
And my javascript
```
$(document).ready(function($) {
var loadbuttonBlogItems = $('#loadmore-blog-items');
loadbuttonBlogItems.on('click', function() {
$(this).addClass('loading');
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
dataType: 'html',
data: {
action: 'get_blog_items',
offset: $('body > div.page-wrap > section.blog-listing > ul').children().length
},
})
.done(function(data) {
console.log(data);
$('.blog-listing ul').append($.parseHTML(data))
})
.fail(function() {
console.log("error occured while loading more blog items");
})
.always(function() {
console.log("ajax call finished");
$(loadbuttonBlogItems).removeClass('loading');
});
})
});
``` | ```
function add_ajax_actions() {
add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );
}
add_action( 'admin_init', 'add_ajax_actions' );
```
`admin_init` only runs when the admin area is initialised. Logged out people can't access wp-admin, so `add_action( 'wp_ajax_nopriv_get_blog_items', 'get_blog_items' );` never runs. Move the add\_action call out of that function and remove the `add_ajax_actions` function and it should work.
Have you considered using the REST API instead? |
252,765 | <p>I plan to bulid up a nice developer environment and for this I need to clone the actual running website to a 100% into a <code>dev</code> directory.</p>
<p>I've now uploaded the same version of wordpress as on my running site and wondering if I could enter the same database and the same prefix as for the running site while running through the installation process. My goal is to connect the development website to the same database, so that it displays the same articles as the running website. Both sites should be in sync in terms of database content!</p>
<p>But I fear that it overwrites everything in my database and that I lose my data (I've got a backup, but I don't want down-time of the real website), so I'm asking you: What will happen if I enter the same details that are used by the running website? Will the development website display all the existing articles or will it overwrite everything in the database?</p>
| [
{
"answer_id": 252766,
"author": "kirillrocks",
"author_id": 111056,
"author_profile": "https://wordpress.stackexchange.com/users/111056",
"pm_score": 0,
"selected": false,
"text": "<p>If you production server allows database connection from anywhere - it will connect. but every update y... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252765",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93282/"
] | I plan to bulid up a nice developer environment and for this I need to clone the actual running website to a 100% into a `dev` directory.
I've now uploaded the same version of wordpress as on my running site and wondering if I could enter the same database and the same prefix as for the running site while running through the installation process. My goal is to connect the development website to the same database, so that it displays the same articles as the running website. Both sites should be in sync in terms of database content!
But I fear that it overwrites everything in my database and that I lose my data (I've got a backup, but I don't want down-time of the real website), so I'm asking you: What will happen if I enter the same details that are used by the running website? Will the development website display all the existing articles or will it overwrite everything in the database? | Based on your question, I am not exactly sure where your local build sits right now.
This answer is assuming you are starting from scratch, but have a copy of a working wordpress website on a live web server, and working on a mac.
You need to install a web server onto your local computer. I am recommending MAMP.
<https://www.mamp.info/en/>
After getting mamp installed your next step would be to configure the `root` folder for your web server, we will move forward with the default settings `Applications/MAMP/htdocs/`
You will then need some sort of FTP client. Filezilla, Cyberduck, etc. login to your production server, and download the entire website ( probably something like `public_html/your_site/` ) into a new folder withing the MAMP root ie: `/Applications/MAMP/htdocs/your_site`
You will then need to log into a SQL client to download a copy of your wordpress database, depending on your web hosting provider, they should have something called `phpmyadmin`. you will need to download the entire `database.sql` file to your local machine, lets say save it to your `desktop`.
Take a backup too at this point, just in case.
From there you will need to navigate to `phpmyadmin` through mamp on your local machine, and upload the .sql file to your local SQL database. if you are comfortable with the command prompt, this will work wonders...
```
/applications/MAMP/library/bin/mysql -u root -p wordpress_db < /Users/you/Desktop/backupDB.sql
```
if not, you can compress and upload, if the db is huge, you might need to break down the structure, & content into two different downloads & uploads, respectively
You will then to run a few SQL queries to change some core options about your wordpress install, ( to configure for local build )
```
UPDATE wp_options SET option_value="http://newdomain.com" WHERE option_name="siteurl";
UPDATE wp_options SET option_value="http://newdomain.com" WHERE option_name="home";
UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');
```
`new domain` will be something like, `localhost/your_site`
You then need to update your `wp-config.php` file to pull from the correct database on your local machine.
```
define( 'DB_NAME', 'wordpress_db' ); // only if you changed db name (don't)
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', 'root' );
define( 'DB_HOST', 'localhost' );
```
Now, I believe your `localhost/your_site` should be working, in the event that only the home page is working, and none of the other pages are, you may need to configure your .htaccess file as follows ( at the same root level as `wp-config.php` )
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /your_site/index.php [L]
</IfModule>
```
So at this point you will have a exact copy of your live website.... now how to sync? .....
check out this plugin... <https://github.com/wp-sync-db/wp-sync-db>
will need to install on your live site, and dev site.
Once active it will allow you to pull your live database into your dev database. you will need to configure an `api key` on your live site, and configure settings to allow for a `pull` then copy that api key and paste into dev site plugin settings ( `tools > migrate-db` ) sync once or twice per day.
please note: I do not recommend pushing your local db to your live db. I only ever pull my live db into my local build.
I hope this tutorial worked for you. |
252,774 | <p>Simple question: I know this can be achieved with a hook somewhere, but I'm having trouble tracking down exactly where I need to look to implement it. Basically, I need to hook into the featured image / thumbnail hook and update the image URL on the fly. Can someone lend a hand on how I might achieve this with the hook system?</p>
<p>I've essentially created a post inheritance plugin whereby an author can create a template and then mass generate new posts that all inherit from this template. These generated posts are fully dynamic in that at runtime in the public view, my plugin fires and checks to see if the active post is template-based. If it is, the plugin grabs the template's content and inserts that into the currently viewed post. This is working great for the title and text replacement already. Now what I need to do is to display a featured image for these posts, again based on the template's featured image. I don't want to actually update these posts in the DB, I simply need to develop it so that when a template calls <code>the_post_thumbnail</code>, my plugin fires and inserts the image automatically. </p>
<p>I hope that clears it up a bit.</p>
| [
{
"answer_id": 252783,
"author": "Vishal Kumar Sahu",
"author_id": 101300,
"author_profile": "https://wordpress.stackexchange.com/users/101300",
"pm_score": 0,
"selected": false,
"text": "<p>With PHP it is possible... Just create a function which copies your featured image and renames it... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252774",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27041/"
] | Simple question: I know this can be achieved with a hook somewhere, but I'm having trouble tracking down exactly where I need to look to implement it. Basically, I need to hook into the featured image / thumbnail hook and update the image URL on the fly. Can someone lend a hand on how I might achieve this with the hook system?
I've essentially created a post inheritance plugin whereby an author can create a template and then mass generate new posts that all inherit from this template. These generated posts are fully dynamic in that at runtime in the public view, my plugin fires and checks to see if the active post is template-based. If it is, the plugin grabs the template's content and inserts that into the currently viewed post. This is working great for the title and text replacement already. Now what I need to do is to display a featured image for these posts, again based on the template's featured image. I don't want to actually update these posts in the DB, I simply need to develop it so that when a template calls `the_post_thumbnail`, my plugin fires and inserts the image automatically.
I hope that clears it up a bit. | HTML generated by `the_post_thumbnail()` & `get_the_post_thumbnail()` can be altered using the `post_thumbnail_html` filter. This works even when there is no post thumbnail. Example:
```
/**
* Filters the post thumbnail HTML.
*
* @since 2.9.0
*
* @param string $html The post thumbnail HTML.
* @param int $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string|array $size The post thumbnail size. Image size or array of width and height
* values (in that order). Default 'post-thumbnail'.
* @param string $attr Query string of attributes.
*/
function wpse_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
// Optionally add any logic here for determining what markup to output.
// $html will be an empty string if there is no post thumbnail.
$new_html = '<img src="https://placekitten.com/g/600/600" alt="kitten">';
return $new_html;
}
add_action( 'post_thumbnail_html', 'wpse_post_thumbnail_html', 10, 5 );
```
The above solution requires that the theme is calling `the_post_thumbnail()`, but it will work when the post does not have a thumbnail associated with it.
Note that the solution above would not work in the example below if the post does not have a thumbnail. Here, the conditional statement prevents `has_post_thumbnail()` from being called:
```
// the_post_thumbnail() will only be called if the post has a thumbnail.
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'large' );
}
```
Alternate technique (alters src value for existing featured images)
-------------------------------------------------------------------
The `wp_get_attachment_image_src` filter allows for the `src` of an attachment to be modified.
This powerful filter affects all attachment image src values, so it is necessary to add/remove the callback function attached to `wp_get_attachment_image_src` based on the desired conditions.
The `begin_fetch_post_thumbnail_html` and `end_fetch_post_thumbnail_html` actions are perfect for this.
Here's some example code that changes the featured image based on the post id. You can modify this code to use whatever logic is necessary to determine when the `wpse_wp_get_attachment_image_src` callback should be added and removed.
```
/**
* Fires before fetching the post thumbnail HTML.
*
* Provides "just in time" filtering of all filters in wp_get_attachment_image().
*
* @since 2.9.0
*
* @param int $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string|array $size The post thumbnail size. Image size or array of width
* and height values (in that order). Default 'post-thumbnail'.
*/
function wpse_begin_fetch_post_thumbnail_html( $post_id, $post_thumbnail_id, $size ) {
// For example, if the post id is 1479, we will add our callback to modify the image.
// You could use whatever logic you need to determine if the filter should be added.
if ( 1479 === $post_id ) {
add_filter( 'wp_get_attachment_image_src', 'wpse_wp_get_attachment_image_src', 10, 4 );
}
}
add_action( 'begin_fetch_post_thumbnail_html', 'wpse_begin_fetch_post_thumbnail_html', 10, 3 );
/**
* Fires after fetching the post thumbnail HTML.
*
* @since 2.9.0
*
* @param int $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string|array $size The post thumbnail size. Image size or array of width
* and height values (in that order). Default 'post-thumbnail'.
*/
function wpse_end_fetch_post_thumbnail_html( $post_id, $post_thumbnail_id, $size ) {
// Now we remove the callback so that it only affects the desired post.
if ( 1479 === $post_id ) {
remove_filter( 'wp_get_attachment_image_src', 'wpse_wp_get_attachment_image_src', 10, 4 );
}
}
add_action( 'end_fetch_post_thumbnail_html', 'wpse_end_fetch_post_thumbnail_html', 10, 3 );
/**
* Filters the image src result.
*
*
* @param array|false $image Either array with src, width & height, icon src, or false.
* @param int $attachment_id Image attachment ID.
* @param string|array $size Size of image. Image size or array of width and height values
* (in that order). Default 'thumbnail'.
* @param bool $icon Whether the image should be treated as an icon. Default false.
*/
function wpse_wp_get_attachment_image_src( $image, $attachment_id, $size, $icon ) {
$image[0] = 'https://placekitten.com/g/600/600';
return $image;
}
``` |
252,799 | <p>Is there a way to disable the edit shortcut buttons that was added in WordPress 4.7?</p>
<p>I noticed they have a class <code>customize-partial-edit-shortcut-button</code> and I can add <code>display:none</code> in css but trying to find a solution in php.</p>
<p><a href="https://i.stack.imgur.com/qfJZ2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qfJZ2.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 252800,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": -1,
"selected": false,
"text": "<p>This featured is enabled by just adding theme support feature. Here is the code</p>\n\n<pre><code>add_t... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252799",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111079/"
] | Is there a way to disable the edit shortcut buttons that was added in WordPress 4.7?
I noticed they have a class `customize-partial-edit-shortcut-button` and I can add `display:none` in css but trying to find a solution in php.
[](https://i.stack.imgur.com/qfJZ2.png) | The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:
```
add_action( 'wp_enqueue_scripts', function () {
$js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';
wp_add_inline_script( 'customize-selective-refresh', $js );
} );
```
This will work for any theme. |
252,816 | <p>I have a rtl.css file for my theme. when i change site language
to Persian (from settings), rtl.css loaded and work properly.But i want to keep in english lanuage and load rtl.css file. How i do it? when language change, what happens?
please help me.
Tnx a lot.</p>
| [
{
"answer_id": 252800,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": -1,
"selected": false,
"text": "<p>This featured is enabled by just adding theme support feature. Here is the code</p>\n\n<pre><code>add_t... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111093/"
] | I have a rtl.css file for my theme. when i change site language
to Persian (from settings), rtl.css loaded and work properly.But i want to keep in english lanuage and load rtl.css file. How i do it? when language change, what happens?
please help me.
Tnx a lot. | The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:
```
add_action( 'wp_enqueue_scripts', function () {
$js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';
wp_add_inline_script( 'customize-selective-refresh', $js );
} );
```
This will work for any theme. |
252,825 | <p>I would like to know the best part of the code to catch a 404 that doesn't match a template.
However at this point I will check for the url string and output my own dynamic html if it matches a pattern. It is DYNAMIC content because there is no content in the wordpress backend for it. So I am looking to echo html and exit if it matches. If not then continue and 404 as normal.</p>
<p>In reference to this question too.
<a href="https://wordpress.stackexchange.com/questions/252289/dynamic-url-generates-dynamic-content/252293">Dynamic URL generates dynamic content</a></p>
<p>TY</p>
| [
{
"answer_id": 252800,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": -1,
"selected": false,
"text": "<p>This featured is enabled by just adding theme support feature. Here is the code</p>\n\n<pre><code>add_t... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252825",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96548/"
] | I would like to know the best part of the code to catch a 404 that doesn't match a template.
However at this point I will check for the url string and output my own dynamic html if it matches a pattern. It is DYNAMIC content because there is no content in the wordpress backend for it. So I am looking to echo html and exit if it matches. If not then continue and 404 as normal.
In reference to this question too.
[Dynamic URL generates dynamic content](https://wordpress.stackexchange.com/questions/252289/dynamic-url-generates-dynamic-content/252293)
TY | The simplest way to disable edit shortcuts without unwanted side effects is to no-op override the JS function that generates them in the first place. You can do this from PHP as follows:
```
add_action( 'wp_enqueue_scripts', function () {
$js = 'wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};';
wp_add_inline_script( 'customize-selective-refresh', $js );
} );
```
This will work for any theme. |
252,849 | <p>I've done numerous WP sites, written my own plugins, run my own server, etc etc.</p>
<p>But I have not seen this before. I just installed a fresh 4.7.1 and installed the <a href="http://www.newsmartwave.net/?theme=porto_wp" rel="nofollow noreferrer">Proto theme</a> and all its plugins.</p>
<p>When I went to add media files, I got:</p>
<pre><code>Maximum upload file size: 2 KB.
</code></pre>
<p>I deactivated all plugins one by one...no dice. My PHP memory limit is set to 256MB for this installation via wp_config.php.</p>
<p>Googling the 2 KB limit turned up no results. </p>
<p>Anyone seen this before or know how to fix this limit?</p>
| [
{
"answer_id": 252857,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>Three things you need to check.</p>\n\n<p><code>upload_max_filesize</code>, <code>memory_limit</code> and <cod... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111117/"
] | I've done numerous WP sites, written my own plugins, run my own server, etc etc.
But I have not seen this before. I just installed a fresh 4.7.1 and installed the [Proto theme](http://www.newsmartwave.net/?theme=porto_wp) and all its plugins.
When I went to add media files, I got:
```
Maximum upload file size: 2 KB.
```
I deactivated all plugins one by one...no dice. My PHP memory limit is set to 256MB for this installation via wp\_config.php.
Googling the 2 KB limit turned up no results.
Anyone seen this before or know how to fix this limit? | Three things you need to check.
`upload_max_filesize`, `memory_limit` and `post_max_size` in the php.ini configuration file exactly.
All of these three settings limit the maximum size of data that can be submitted and handled by PHP.
Typically `post_max_size` and `memory_limit` need to be larger than `upload_max_filesize`.
---
This is the function in WordPress that defines the constant you saw:
```
File: wp-includes/media.php
2843: /**
2844: * Determines the maximum upload size allowed in php.ini.
2845: *
2846: * @since 2.5.0
2847: *
2848: * @return int Allowed upload size.
2849: */
2850: function wp_max_upload_size() {
2851: $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2852: $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2853:
2854: /**
2855: * Filters the maximum upload size allowed in php.ini.
2856: *
2857: * @since 2.5.0
2858: *
2859: * @param int $size Max upload size limit in bytes.
2860: * @param int $u_bytes Maximum upload filesize in bytes.
2861: * @param int $p_bytes Maximum size of POST data in bytes.
2862: */
2863: return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2864: }
``` |
252,865 | <p>I want to make a custom WP_Query using custom taxonomy terms ID´s.</p>
<p>Example of the term’s ID’s : 19,18,214,226,20</p>
<p>Why does this work:</p>
<pre><code>$query_args = array (
'post_type' => 'works’,
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( 19,18,214,226,20 ),
)
),
);
</code></pre>
<p>It shows all items from all taxonomy terms ID’s,</p>
<p>But this doesn’t:</p>
<p><code>$tax = '19,18,214,226,20';</code></p>
<pre><code>$query_args = array (
'post_type' => 'works',
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( $tax ),
)
),
);
</code></pre>
<p>Using the variable <code>$tax</code> the query result only shows items the first term ID (19), and ignores all the others.</p>
<p>Why does this happens and how can i use the variable in the tax_query instead of hardcode the ID’s ?</p>
| [
{
"answer_id": 252868,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 5,
"selected": true,
"text": "<p>It looks like you are making an array with a single string inside.</p>\n\n<p>Check if making $tax int... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16324/"
] | I want to make a custom WP\_Query using custom taxonomy terms ID´s.
Example of the term’s ID’s : 19,18,214,226,20
Why does this work:
```
$query_args = array (
'post_type' => 'works’,
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( 19,18,214,226,20 ),
)
),
);
```
It shows all items from all taxonomy terms ID’s,
But this doesn’t:
`$tax = '19,18,214,226,20';`
```
$query_args = array (
'post_type' => 'works',
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => array( $tax ),
)
),
);
```
Using the variable `$tax` the query result only shows items the first term ID (19), and ignores all the others.
Why does this happens and how can i use the variable in the tax\_query instead of hardcode the ID’s ? | It looks like you are making an array with a single string inside.
Check if making $tax into an array before passing it will work:
```
$tax = array( 19, 18, 214, 226, 20 );
$query_args = array (
'post_type' => 'works',
'tax_query' => array(
array(
'taxonomy' => 'materials',
'field' => 'term_id',
'terms' => $tax,
)
),
);
```
If you need to make an array from a formatted string, you can use the `explode` PHP function that takes a delimiter and a string, and returns an array, like so:
```
$tax_string = '19,18,214,226,20';
$tax_array = explode( ',', $tax_string );
```
Hope that works! |
252,877 | <p>I've created a new custom post type called <code>doctors</code>. I've been using ACF and pulling these fields to help create my banner. I was wondering what a post would look like if no fields were filled out, so I created a second test post, but I noticed it has all of the same content as my first post.</p>
<p>I feel like I'm writing my function incorrectly, obviously.</p>
<pre><code>function doctor_banner_shortcode() {
$args = array(
'posts_per_page' => 1,
'post_type' => 'doctors',
'post_status' => 'publish'
);
$doctors_query = new WP_Query( $args );
if ( $doctors_query->have_posts() ) :
while ( $doctors_query->have_posts() ) :
$doctors_query->the_post();
$dr_name = get_field( 'practitioner_name' );
$dr_degree = get_field( 'practitioner_title' );
$dr_bio = get_field( 'practitioner_short_bio' );
$dr_cv = get_field( 'practitioner_cv' );
$html_out = '<h1>Dr. ' . $dr_name . '</h1>
<h3">' . $dr_degree . '</h3>
<p>' . $dr_bio . '</p>
<a href="' . $dr_cv . '">' . 'Read CV' . '</a>';
endwhile;
else : // No results
$html_out = "No Doctors Found.";
endif;
wp_reset_query();
return $html_out;
}
add_shortcode( 'doctor_banner', 'doctor_banner_shortcode' );
</code></pre>
<p>Somehow, I think, it's not reading the proper ID of that post to output the correct data. I have two links for my two posts <a href="http://www.ankitdesigns.com/demo/hu/doctors/kevin-kwan/" rel="nofollow noreferrer">here</a> and <a href="http://www.ankitdesigns.com/demo/hu/doctors/test-doctor/" rel="nofollow noreferrer">here</a>.</p>
| [
{
"answer_id": 252881,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you are not supplying the ID into the loop, forcing it to get the first item chronolog... | 2017/01/17 | [
"https://wordpress.stackexchange.com/questions/252877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96257/"
] | I've created a new custom post type called `doctors`. I've been using ACF and pulling these fields to help create my banner. I was wondering what a post would look like if no fields were filled out, so I created a second test post, but I noticed it has all of the same content as my first post.
I feel like I'm writing my function incorrectly, obviously.
```
function doctor_banner_shortcode() {
$args = array(
'posts_per_page' => 1,
'post_type' => 'doctors',
'post_status' => 'publish'
);
$doctors_query = new WP_Query( $args );
if ( $doctors_query->have_posts() ) :
while ( $doctors_query->have_posts() ) :
$doctors_query->the_post();
$dr_name = get_field( 'practitioner_name' );
$dr_degree = get_field( 'practitioner_title' );
$dr_bio = get_field( 'practitioner_short_bio' );
$dr_cv = get_field( 'practitioner_cv' );
$html_out = '<h1>Dr. ' . $dr_name . '</h1>
<h3">' . $dr_degree . '</h3>
<p>' . $dr_bio . '</p>
<a href="' . $dr_cv . '">' . 'Read CV' . '</a>';
endwhile;
else : // No results
$html_out = "No Doctors Found.";
endif;
wp_reset_query();
return $html_out;
}
add_shortcode( 'doctor_banner', 'doctor_banner_shortcode' );
```
Somehow, I think, it's not reading the proper ID of that post to output the correct data. I have two links for my two posts [here](http://www.ankitdesigns.com/demo/hu/doctors/kevin-kwan/) and [here](http://www.ankitdesigns.com/demo/hu/doctors/test-doctor/). | You are querying the entire posts of `doctors` type, and setting the number of posts per page to one. This will obviously always return the same post.
You need to either set the id of the post, or navigate through the loop to find a match. If you are calling this function in single post page, to filter the results based on post id, you should use the function this way:
```
function doctor_banner_shortcode($doctor_id) {
$args = array(
'posts_per_page' => 1,
'post_type' => 'doctors',
'post_status' => 'publish',
'p' => $doctor_id
);
$doctors_query = new WP_Query( $args );
if ( $doctors_query->have_posts() ) :
while ( $doctors_query->have_posts() ) :
$doctors_query->the_post();
$dr_name = get_field( 'practitioner_name' );
$dr_degree = get_field( 'practitioner_title' );
$dr_bio = get_field( 'practitioner_short_bio' );
$dr_cv = get_field( 'practitioner_cv' );
$html_out = '<h1>Dr. ' . $dr_name . '</h1>
<h3">' . $dr_degree . '</h3>
<p>' . $dr_bio . '</p>
<a href="' . $dr_cv . '">' . 'Read CV' . '</a>';
endwhile;
else : // No results
$html_out = "No Doctors Found.";
endif;
wp_reset_query();
return $html_out;
}
add_shortcode( 'doctor_banner', 'doctor_banner_shortcode' );
```
Then you can call your function in the `single.php` template in this way :
`function doctor_banner_shortcode($post->ID)`
If you want to call the function manually in some other page, you should set the ID while calling the function. |
252,920 | <p>I want to change the default WordPress author link (which is /author/user_nicename) to/author/user_id.</p>
<p>And I found it's easy to do that, I achieved this in two ways:</p>
<p>1.I just copy the <code>get_author_posts_url()</code> function from <code>wp-includes/author-template.php</code> and rewrite it in my theme:</p>
<pre><code>function ji_get_user_url($author_id, $author_nicename = '') {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty($link) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $auth_ID;
}else {
if ( '' == $author_nicename ) {
$user = get_userdata($author_id);
if ( !empty($user->user_nicename) )
$author_nicename = $author_id;
}
$link = str_replace('%author%', $author_id, $link);
$link = home_url( user_trailingslashit( $link ) );
}
$link = apply_filters( 'author_link', $link, $author_id, $author_nicename );
return $link;
}
</code></pre>
<p>2.I used the filter:</p>
<pre><code>function chang_author_link($link,$author_id,$author_nicename){
$user_info = get_userdata(get_current_user_id());
$user_id= $user_info->ID;
$link = str_replace($author_nicename, $user_id, $link);
return $link;
}
add_filter('author_link', 'chang_author_link',10,3);
</code></pre>
<p>Either way above can successfully change the default author link to /author/user_id, but that they all returned a 404 not found page! </p>
<p>What happened?</p>
| [
{
"answer_id": 252899,
"author": "fatwombat",
"author_id": 81482,
"author_profile": "https://wordpress.stackexchange.com/users/81482",
"pm_score": 1,
"selected": false,
"text": "<p>I am doing the same thing at the moment and I just use the standard WP login/register systems/pages.</p>\n\... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252920",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105000/"
] | I want to change the default WordPress author link (which is /author/user\_nicename) to/author/user\_id.
And I found it's easy to do that, I achieved this in two ways:
1.I just copy the `get_author_posts_url()` function from `wp-includes/author-template.php` and rewrite it in my theme:
```
function ji_get_user_url($author_id, $author_nicename = '') {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty($link) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $auth_ID;
}else {
if ( '' == $author_nicename ) {
$user = get_userdata($author_id);
if ( !empty($user->user_nicename) )
$author_nicename = $author_id;
}
$link = str_replace('%author%', $author_id, $link);
$link = home_url( user_trailingslashit( $link ) );
}
$link = apply_filters( 'author_link', $link, $author_id, $author_nicename );
return $link;
}
```
2.I used the filter:
```
function chang_author_link($link,$author_id,$author_nicename){
$user_info = get_userdata(get_current_user_id());
$user_id= $user_info->ID;
$link = str_replace($author_nicename, $user_id, $link);
return $link;
}
add_filter('author_link', 'chang_author_link',10,3);
```
Either way above can successfully change the default author link to /author/user\_id, but that they all returned a 404 not found page!
What happened? | I am doing the same thing at the moment and I just use the standard WP login/register systems/pages.
You can use [wp\_signon()](https://developer.wordpress.org/reference/functions/wp_signon/) to do logon.
Then on a standard page, you can create a custom template and use this for retrieving their info: [wp\_get\_current\_user()](https://codex.wordpress.org/Function_Reference/wp_get_current_user)
You will also need to get the customer user meta information you store too using: [get\_user\_meta()](https://codex.wordpress.org/Function_Reference/get_user_meta)
Hope that helps you :) |
252,922 | <p>Why is it that when I attempt to change the URL for searches, it breaks if set to anything other than <code>search</code>?</p>
<pre><code>function bfm_pretty_search () {
if (is_search() && !empty($_GET['s'])) {
wp_redirect(home_url('/search/').urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'bfm_pretty_search');
</code></pre>
<p>So, instead of the url looking like <code>mydomain.com/search/query</code>, I'd like it to be: <code>mydomain.com/results/query</code>, but it doesn't work with anything other than "search"... why?</p>
| [
{
"answer_id": 252924,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 2,
"selected": false,
"text": "<p>To change the search url hook in this function this will replace \"search\" to whatever you want.</p>\n\... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252922",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25735/"
] | Why is it that when I attempt to change the URL for searches, it breaks if set to anything other than `search`?
```
function bfm_pretty_search () {
if (is_search() && !empty($_GET['s'])) {
wp_redirect(home_url('/search/').urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'bfm_pretty_search');
```
So, instead of the url looking like `mydomain.com/search/query`, I'd like it to be: `mydomain.com/results/query`, but it doesn't work with anything other than "search"... why? | To change the search url hook in this function this will replace "search" to whatever you want.
```
add_action( 'init', 'wpse21549_init' );
function wpse21549_init()
{
$GLOBALS['wp_rewrite']->search_base = 'results';
}
```
place this code in your functions.php file and after saving this file. Go to permalink settings page and click on the save button to flush the rewrite rules.
**update**
To modify the search rewrite rules you can hook into the search\_rewrite\_rules filter. You can either add the extra rewrite rules that match post types yourself, or you can change the default "search rewrite structure" to also include the post type and then re-generate the rules (there are four rules: one standard, one with paging and two for feeds).
```
add_filter( 'search_rewrite_rules', 'wpse15418_search_rewrite_rules' );
function wpse15418_search_rewrite_rules( $search_rewrite_rules )
{
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag( '%post_type%', '([^/]+)', 'post_type=' );
$search_structure = $wp_rewrite->get_search_permastruct();
return $wp_rewrite->generate_rewrite_rules( $search_structure . '/section/%post_type%', EP_SEARCH );
}
``` |
252,925 | <p>For the homepage, I'd like the main page background to be the background for the entire page, including the footer.</p>
<p>Please help!?</p>
<p>Reed</p>
<p><a href="https://i.stack.imgur.com/4YifW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4YifW.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 252928,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 1,
"selected": false,
"text": "<p>It's better if you share the the link to your site OR if you can show us the attempts you have made and ... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252925",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111160/"
] | For the homepage, I'd like the main page background to be the background for the entire page, including the footer.
Please help!?
Reed
[](https://i.stack.imgur.com/4YifW.jpg) | It's better if you share the the link to your site OR if you can show us the attempts you have made and the problems which your are facing while doing so.
A suggestion for to do so is to make footer background transparent and apply background image to your .page class which is default wordpress class you can be more specific with by using unique page ID in css and then apply that background.
for example:
```
#example-pageid footer {
background:transparent;
}
#example-pageid {
background_image:url(your/image/
}
``` |
252,947 | <p>I have wordpress template from themeforest and I would like to set it up, just like demo page on themeforest....</p>
<p>I found files like customizer.dat.txt, demo=content.xml, widgets.json ...</p>
<p>they probably serve for this purpose but as I'm newbie in Wordpress, have no idea how to use them.</p>
<p>Can you please help me how to import ? Thank you so much!</p>
| [
{
"answer_id": 252928,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 1,
"selected": false,
"text": "<p>It's better if you share the the link to your site OR if you can show us the attempts you have made and ... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111175/"
] | I have wordpress template from themeforest and I would like to set it up, just like demo page on themeforest....
I found files like customizer.dat.txt, demo=content.xml, widgets.json ...
they probably serve for this purpose but as I'm newbie in Wordpress, have no idea how to use them.
Can you please help me how to import ? Thank you so much! | It's better if you share the the link to your site OR if you can show us the attempts you have made and the problems which your are facing while doing so.
A suggestion for to do so is to make footer background transparent and apply background image to your .page class which is default wordpress class you can be more specific with by using unique page ID in css and then apply that background.
for example:
```
#example-pageid footer {
background:transparent;
}
#example-pageid {
background_image:url(your/image/
}
``` |
252,951 | <p>how to insert data in wordpress using jquery ajax for my plugin, i tried a lot but my action.php page not access global $wpdb, Please tell me where is the problem.</p>
<p>Here is the code of my submenu page of plugin</p>
<pre><code><?php
function pincode()
{
?>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
//url: 'http://localhost/wordpress/wp-content/plugins/arunkumar/action.php',
url : '<?php echo plugin_dir_url(__FILE__).'action.php';?>',
data: userData,
success:function(msg){
if(msg == 'ok'){
alert('User data has been '+statusArr[type]+' successfully.');
//getUsers();
$('.form')[0].reset();
$('.formData').slideUp();
}else{
//alert('Some problem occurred, please try again.');
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+msg+' !</div>');
}
}
});
}
</script>
<div class="panel-heading">States <a href="javascript:void(0);" class="glyphicon glyphicon-plus" id="addLink" onclick="javascript:$('#addForm').slideToggle();"></a></div>
<div class="panel-body none formData" id="addForm">
<h2 id="actionLabel">Add New State</h2>
<form class="form" id="userForm">
<div id="error"></div>
<div class="form-group">
<label>State Name</label>
<input type="text" class="form-control" placeholder="Enter State Name" name="name" id="name"/>
</div>
<a href="javascript:void(0);" class="btn btn-warning" onclick="$('#addForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add State</a>
</form>
</div>
<?php
}
</code></pre>
<p>and this is action.php code where insert code is applied but it show " Fatal error: Call to a member function insert() on null " error</p>
<pre><code> <?php
if(isset($_POST['action_type']) && !empty($_POST['action_type'])){
if($_POST['action_type'] == 'add'){
//echo $insert?'ok':'err';
global $wpdb;
$state_name = $_POST['name'];
$wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );
$status = $wpdb->insert_id;
echo $status ? 'ok' : var_dump($wpdb);
}
</code></pre>
| [
{
"answer_id": 252957,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 2,
"selected": false,
"text": "<p>The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is exp... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110592/"
] | how to insert data in wordpress using jquery ajax for my plugin, i tried a lot but my action.php page not access global $wpdb, Please tell me where is the problem.
Here is the code of my submenu page of plugin
```
<?php
function pincode()
{
?>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
//url: 'http://localhost/wordpress/wp-content/plugins/arunkumar/action.php',
url : '<?php echo plugin_dir_url(__FILE__).'action.php';?>',
data: userData,
success:function(msg){
if(msg == 'ok'){
alert('User data has been '+statusArr[type]+' successfully.');
//getUsers();
$('.form')[0].reset();
$('.formData').slideUp();
}else{
//alert('Some problem occurred, please try again.');
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+msg+' !</div>');
}
}
});
}
</script>
<div class="panel-heading">States <a href="javascript:void(0);" class="glyphicon glyphicon-plus" id="addLink" onclick="javascript:$('#addForm').slideToggle();"></a></div>
<div class="panel-body none formData" id="addForm">
<h2 id="actionLabel">Add New State</h2>
<form class="form" id="userForm">
<div id="error"></div>
<div class="form-group">
<label>State Name</label>
<input type="text" class="form-control" placeholder="Enter State Name" name="name" id="name"/>
</div>
<a href="javascript:void(0);" class="btn btn-warning" onclick="$('#addForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add State</a>
</form>
</div>
<?php
}
```
and this is action.php code where insert code is applied but it show " Fatal error: Call to a member function insert() on null " error
```
<?php
if(isset($_POST['action_type']) && !empty($_POST['action_type'])){
if($_POST['action_type'] == 'add'){
//echo $insert?'ok':'err';
global $wpdb;
$state_name = $_POST['name'];
$wpdb->insert( 'state',array( 'state_name' => $state_n),array('%s') );
$status = $wpdb->insert_id;
echo $status ? 'ok' : var_dump($wpdb);
}
``` | The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <https://codex.wordpress.org/AJAX_in_Plugins>
I have tried this and it works well. |
252,963 | <p>How to make this query more simplest and in one query? </p>
<p>Problem - only topics has a meta_key 'include_newsletter_feed'<br>
So i need get all posts ("product", "post", "page") excluding categories (124, 52)<br>
And join all topics with meta. </p>
<p>Example ugly code</p>
<pre><code>$arg = array(
"post_type" => array("product", "post", "page"),
"posts_per_page" => 3,
'category__not_in' => array( 124 /*Gallery*/, 52 /* Discounts */ )
);
$_posts = get_posts($arg);
$arg = array(
"post_type" => "topic",
"posts_per_page" => $nimbus_posts_on_home,
'meta_key' => 'include_newsletter_feed',
'meta_value' => 'true',
);
$_topicts = get_posts($arg);
$_all_posts = array_merge ($_topicts, $_posts);
$ids = array();
foreach($_all_posts as $_post) {
$ids[] = $_post->ID;
}
/* Final query */
$wp_query = new WP_Query(array( "post_type" => array("product", "post", "page", "topic"), "post__in" => $ids ));
</code></pre>
| [
{
"answer_id": 252957,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 2,
"selected": false,
"text": "<p>The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is exp... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252963",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111184/"
] | How to make this query more simplest and in one query?
Problem - only topics has a meta\_key 'include\_newsletter\_feed'
So i need get all posts ("product", "post", "page") excluding categories (124, 52)
And join all topics with meta.
Example ugly code
```
$arg = array(
"post_type" => array("product", "post", "page"),
"posts_per_page" => 3,
'category__not_in' => array( 124 /*Gallery*/, 52 /* Discounts */ )
);
$_posts = get_posts($arg);
$arg = array(
"post_type" => "topic",
"posts_per_page" => $nimbus_posts_on_home,
'meta_key' => 'include_newsletter_feed',
'meta_value' => 'true',
);
$_topicts = get_posts($arg);
$_all_posts = array_merge ($_topicts, $_posts);
$ids = array();
foreach($_all_posts as $_post) {
$ids[] = $_post->ID;
}
/* Final query */
$wp_query = new WP_Query(array( "post_type" => array("product", "post", "page", "topic"), "post__in" => $ids ));
``` | The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <https://codex.wordpress.org/AJAX_in_Plugins>
I have tried this and it works well. |
252,968 | <p>Below is my code in which everything is working fine except when clicking read more button it's doing nothing</p>
<pre><code><?php get_header() ; ?>
<section class="container">
<div class="row">
<div class="col-sm-8">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article class="blog">
<div class="blog-meta">
<h2 class="blog-meta-title"><a href="<?php the_permalink() ; ?>"><?php the_title() ; ?></a></h2>
<p class="blog-meta-detail">
Posted by <?php the_author_posts_link(); ?>
on <?php the_time('F j, Y'); ?>
Category <?php the_category(', ') ; ?>
Tag <?php if ( is_tag() ) {
the_tags('',', ','');
} else {
echo("No Tags Found");
} ?>
</p>
</div> <!-- .blog-meta -->
<?php if ( has_post_thumbnail() ) : ?>
<div class="blog-img">
<?php the_post_thumbnail('full',array(
'class' => 'img-responsive',
)); ?>
</div> <!-- .blog-img -->
<?php endif ; ?> <!-- if ends here of thumbnail -->
<div class="blog-excerpt">
<?php the_excerpt() ; ?>
</div> <!-- .blog-excerpt -->
<div class="blog-more">
<button class="btn btn-primary" href="<?php the_permalink() ; ?>">Read More</button>
</div> <!-- .blog-more -->
<div class="blog-hr">
<hr>
</div> <!-- .blog-hr -->
</article> <!-- .blog -->
<?php endwhile; else : ?> <!-- while ends here of post loop and else starts -->
<article class="blog">
<p><?php _e( 'Sorry, no posts found yo can always start writing' ); ?></p>
</article> <!-- .blog -->
<?php endif; ?> <!-- if ends here post loop -->
</div> <!-- .col-sm-8 -->
<div class="col-sm-4">
<?php get_sidebar() ; ?>
</div> <!-- .col-sm-4 -->
</div> <!-- .row -->
</section> <!-- .container -->
<?php get_footer() ; ?>
</code></pre>
<p>looks like dev in dev tool also link is showing correctly on read more button
<a href="https://i.stack.imgur.com/iRi1i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iRi1i.png" alt="enter image description here"></a>
thanks in advance for help.</p>
| [
{
"answer_id": 252957,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 2,
"selected": false,
"text": "<p>The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is exp... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100679/"
] | Below is my code in which everything is working fine except when clicking read more button it's doing nothing
```
<?php get_header() ; ?>
<section class="container">
<div class="row">
<div class="col-sm-8">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<article class="blog">
<div class="blog-meta">
<h2 class="blog-meta-title"><a href="<?php the_permalink() ; ?>"><?php the_title() ; ?></a></h2>
<p class="blog-meta-detail">
Posted by <?php the_author_posts_link(); ?>
on <?php the_time('F j, Y'); ?>
Category <?php the_category(', ') ; ?>
Tag <?php if ( is_tag() ) {
the_tags('',', ','');
} else {
echo("No Tags Found");
} ?>
</p>
</div> <!-- .blog-meta -->
<?php if ( has_post_thumbnail() ) : ?>
<div class="blog-img">
<?php the_post_thumbnail('full',array(
'class' => 'img-responsive',
)); ?>
</div> <!-- .blog-img -->
<?php endif ; ?> <!-- if ends here of thumbnail -->
<div class="blog-excerpt">
<?php the_excerpt() ; ?>
</div> <!-- .blog-excerpt -->
<div class="blog-more">
<button class="btn btn-primary" href="<?php the_permalink() ; ?>">Read More</button>
</div> <!-- .blog-more -->
<div class="blog-hr">
<hr>
</div> <!-- .blog-hr -->
</article> <!-- .blog -->
<?php endwhile; else : ?> <!-- while ends here of post loop and else starts -->
<article class="blog">
<p><?php _e( 'Sorry, no posts found yo can always start writing' ); ?></p>
</article> <!-- .blog -->
<?php endif; ?> <!-- if ends here post loop -->
</div> <!-- .col-sm-8 -->
<div class="col-sm-4">
<?php get_sidebar() ; ?>
</div> <!-- .col-sm-4 -->
</div> <!-- .row -->
</section> <!-- .container -->
<?php get_footer() ; ?>
```
looks like dev in dev tool also link is showing correctly on read more button
[](https://i.stack.imgur.com/iRi1i.png)
thanks in advance for help. | The code you have shared can work in core PHP and not in Wordpress. Using AJAX in Wordpress plugin is explained in Wordpress documentation. Please refer - <https://codex.wordpress.org/AJAX_in_Plugins>
I have tried this and it works well. |
252,976 | <p>I am trying to fetch more posts on click via ajax. In my functions I have localised the script </p>
<pre><code>wp_enqueue_script( 'news', get_template_directory_uri().'/news/js/news.js', '', '', true );
//Localise script for ajax call
wp_localize_script( 'news', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => 'No Older Posts Found',
));
</code></pre>
<p>My Function for querying posts</p>
<pre><code>function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 2;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'paged' => $page
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .='<article class="post-container clearfix">
<div class="post-inner clearfix">
<div class="post-image">
'.get_the_post_thumbnail().'
</div>
<h1>'.the_title().'</h1>
<span class="date">Date: '.get_the_date().'</span>
<br>
<span class="author">Author: '.the_author().'</span>
<br>
'.get_custom_excerpt(get_the_content()).'
<a class="read-more" href="'.get_the_permalink().'" title="Read More"><img src="'.get_template_directory_uri().'/news/img/read-more.png" alt="Read More"></a>
</div>
</article>';
endwhile;
endif;
wp_reset_postdata();
echo $out;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
</code></pre>
<p>and then my jQuery</p>
<pre><code>jQuery(document).ready(function(){
var ppp = 2; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
jQuery.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
console.log(data);
var $data = jQuery(data);
if($data.length){
jQuery(".posts-wrapper").append($data);
jQuery(".load-more").attr("disabled",false);
} else{
jQuery(".load-more").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
jQuery(".load-more").on("click",function(e){ // When btn is pressed.
jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
load_posts();
e.preventDefault();
});
});
</code></pre>
<p>The ajax response is always 0. Could anyone help please. </p>
| [
{
"answer_id": 252988,
"author": "Anton Pedan",
"author_id": 105771,
"author_profile": "https://wordpress.stackexchange.com/users/105771",
"pm_score": 2,
"selected": false,
"text": "<p>Try die() function in the end of PHP function. It will helps.</p>\n\n<p>UPD: I<code>ve made some simple... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/252976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111192/"
] | I am trying to fetch more posts on click via ajax. In my functions I have localised the script
```
wp_enqueue_script( 'news', get_template_directory_uri().'/news/js/news.js', '', '', true );
//Localise script for ajax call
wp_localize_script( 'news', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => 'No Older Posts Found',
));
```
My Function for querying posts
```
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 2;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'paged' => $page
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .='<article class="post-container clearfix">
<div class="post-inner clearfix">
<div class="post-image">
'.get_the_post_thumbnail().'
</div>
<h1>'.the_title().'</h1>
<span class="date">Date: '.get_the_date().'</span>
<br>
<span class="author">Author: '.the_author().'</span>
<br>
'.get_custom_excerpt(get_the_content()).'
<a class="read-more" href="'.get_the_permalink().'" title="Read More"><img src="'.get_template_directory_uri().'/news/img/read-more.png" alt="Read More"></a>
</div>
</article>';
endwhile;
endif;
wp_reset_postdata();
echo $out;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
```
and then my jQuery
```
jQuery(document).ready(function(){
var ppp = 2; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
jQuery.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
console.log(data);
var $data = jQuery(data);
if($data.length){
jQuery(".posts-wrapper").append($data);
jQuery(".load-more").attr("disabled",false);
} else{
jQuery(".load-more").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
jQuery(".load-more").on("click",function(e){ // When btn is pressed.
jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
load_posts();
e.preventDefault();
});
});
```
The ajax response is always 0. Could anyone help please. | Try die() function in the end of PHP function. It will helps.
UPD: I`ve made some simple version of your problem code to check it and it works. I think it will helps you.
You are able to change inner PHP script to your logic and it won`t returns 0.
PHP:
```
function more_post_ajax(){
echo "Hello";
die();
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
function custom_scripts_init(){
wp_enqueue_script( 'custom', get_template_directory_uri().'/assets/js/custom.js', array('jquery') );
wp_localize_script( 'custom', 'ajaxPosts', array(
'customUrl' => admin_url( 'admin-ajax.php' ),
'noposts' => 'No Older Posts Found',
));
}
add_action('wp_footer', 'custom_scripts_init');
```
JQuery:
```
jQuery(document).ready(function(){
jQuery("#page").append("<button type='button' class='load-more'/>");
var ppp = 2; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
jQuery.ajax({
type: "POST",
dataType: "html",
url: ajaxPosts.customUrl,
data: str,
success: function(data){
console.log(data);
},
error : function(jqXHR, textStatus, errorThrown) {
//$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
jQuery(".load-more").on("click",function(e){ // When btn is pressed.
// jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
load_posts();
e.preventDefault();
});
```
}); |
253,032 | <p>I have two wordpress installs each on their own sub domain.</p>
<p><strong>sub1.domain.com</strong> and <strong>sub2.domain.com</strong></p>
<p>I want to share the login information between sub1 and sub2. I already have configured them to use the same MySQL database, and they use the same database table.</p>
<p>I am able to log in on both websites with the same credentials.</p>
<p>Sub2's wp-config.php file has the following code:</p>
<pre><code>define('CUSTOM_USER_TABLE', 'wp_c_users');
define('CUSTOM_USERMETA_TABLE', 'wp_c_usermeta');
</code></pre>
<p>This all works great. My problem, is that the cookies are not being shared between the sites. Instead of sharing the cookies both sites just delete the others and create a new cookie.</p>
<p>I added the following code to both sub1 and sub2's wp-config.php:</p>
<pre><code>define('COOKIEPATH','domain.com/'); // Replace with your initial domain name
define('SITECOOKIEPATH','domain.com/'); // Replace with your initial domain name
define( 'COOKIEHASH', md5( 'Y@^ET#UF!RG7#KQXP04^WF' ) );
define('COOKIE_DOMAIN', 'domain.com');
</code></pre>
<p>When a user logs in to sub1, the cookie is created just fine, then when I go to sub2.domain.com, I am not also logged in on this site.</p>
<p>When I then try to log in to sub2.domain.com, it deletes sub1's cookies and overwrites them.</p>
<p>How can I get these two wordpress installations to use the same cookie instead of overwriting eachothers??</p>
<p>Any help much appreciated!</p>
| [
{
"answer_id": 264504,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": false,
"text": "<p>Today, I've posted a working solution for exactly the same problem. You can see it here: <a hr... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/253032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111226/"
] | I have two wordpress installs each on their own sub domain.
**sub1.domain.com** and **sub2.domain.com**
I want to share the login information between sub1 and sub2. I already have configured them to use the same MySQL database, and they use the same database table.
I am able to log in on both websites with the same credentials.
Sub2's wp-config.php file has the following code:
```
define('CUSTOM_USER_TABLE', 'wp_c_users');
define('CUSTOM_USERMETA_TABLE', 'wp_c_usermeta');
```
This all works great. My problem, is that the cookies are not being shared between the sites. Instead of sharing the cookies both sites just delete the others and create a new cookie.
I added the following code to both sub1 and sub2's wp-config.php:
```
define('COOKIEPATH','domain.com/'); // Replace with your initial domain name
define('SITECOOKIEPATH','domain.com/'); // Replace with your initial domain name
define( 'COOKIEHASH', md5( 'Y@^ET#UF!RG7#KQXP04^WF' ) );
define('COOKIE_DOMAIN', 'domain.com');
```
When a user logs in to sub1, the cookie is created just fine, then when I go to sub2.domain.com, I am not also logged in on this site.
When I then try to log in to sub2.domain.com, it deletes sub1's cookies and overwrites them.
How can I get these two wordpress installations to use the same cookie instead of overwriting eachothers??
Any help much appreciated! | Today, I've posted a working solution for exactly the same problem. You can see it here: [How to share WordPress session and cookies between domain and subdomain?](https://wordpress.stackexchange.com/questions/130753/how-to-share-wordpress-session-and-cookies-between-domain-and-subdomain/264490#264490). I use this method on several of my own websites. |
253,037 | <p>I have used this function to change the number of posts per page on a category page, but I can't get it to work for a <strong>sub</strong>-category page. </p>
<p>I'm trying to show 6 posts on the sub-category page and 12 on the parent category page. </p>
<pre><code>function my_post_queries( $query ) {
if (!is_admin() && $query->is_main_query()){
if(cat_is_ancestor_of( 7, get_query_var( 'cat' ) ) ){
$query->set('posts_per_page', 6);
}
if(is_category( '7' )){
$query->set('posts_per_page', 12);
}
}
}
add_action( 'pre_get_posts', 'my_post_queries' );
</code></pre>
<p>When I use cat_is_ancestor_of on the archive page to change the layout of the sub-category page, it works, but when I use it in that function it doesn't. </p>
| [
{
"answer_id": 264504,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": false,
"text": "<p>Today, I've posted a working solution for exactly the same problem. You can see it here: <a hr... | 2017/01/18 | [
"https://wordpress.stackexchange.com/questions/253037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78026/"
] | I have used this function to change the number of posts per page on a category page, but I can't get it to work for a **sub**-category page.
I'm trying to show 6 posts on the sub-category page and 12 on the parent category page.
```
function my_post_queries( $query ) {
if (!is_admin() && $query->is_main_query()){
if(cat_is_ancestor_of( 7, get_query_var( 'cat' ) ) ){
$query->set('posts_per_page', 6);
}
if(is_category( '7' )){
$query->set('posts_per_page', 12);
}
}
}
add_action( 'pre_get_posts', 'my_post_queries' );
```
When I use cat\_is\_ancestor\_of on the archive page to change the layout of the sub-category page, it works, but when I use it in that function it doesn't. | Today, I've posted a working solution for exactly the same problem. You can see it here: [How to share WordPress session and cookies between domain and subdomain?](https://wordpress.stackexchange.com/questions/130753/how-to-share-wordpress-session-and-cookies-between-domain-and-subdomain/264490#264490). I use this method on several of my own websites. |
253,078 | <p>I'm getting this in my json response</p>
<pre><code>"main_image":
[
"11125,11122,11123,11127,11128"
],
</code></pre>
<p>Those are the ID's of my post, I need to get the URL of each ID in the 'thumbnail' size. I did't find any solution, just this code but It's more for Custom Meta of a plugin.</p>
<pre><code>function xxx_past_poss_custom_metadata( $post_response, $post, $context ) {
$meta = get_post_custom( $post['ID'] );
$custom_fields = array();
$xxx_image_gallery = array();
foreach ( $meta['xxx_cmb_image_gallery'] as $key => $value ) {
$value = wp_get_attachment_url($value);
$xxx_image_gallery[ $key ] = $value;
};
foreach ( $meta as $key => $value ) {
// Replace 'xxx_' with any custom metakey prefix (ie. '_' for private metadata's)
if ( 'xxx_' !== substr( $key, 0, 1 ) ) {
$custom_fields[ $key ] = $value;
};
}
$post_response['xxx_image_gallery'] = $xxx_image_gallery;
$post_response['custom_fields'] = $custom_fields;
return $post_response;
}
add_filter( 'json_prepare_post', 'xxx_past_poss_custom_metadata', 10, 3 );
</code></pre>
<p>My meta it's called "media_gallery".</p>
<p>Any help will be very appreciated.</p>
<p>[UPDATE]</p>
<p>Seems like I wasn't even modifying my json response because of a plugin I had activated, turning it off made me declare my meta in my functions.php file and no I have this.</p>
<pre><code>add_action('rest_api_init', 'register_custom_fields', 1, 1);
function register_custom_fields(){
register_rest_field(
'job_listing',
'thumbnail',
array(
'get_callback' => 'show_image'
)
);
}
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
return $main_image;
}
</code></pre>
<p>I can now modify the response but I still haven't been able to turn all this ID's: "11125,11122,11123,11127,11128" into URL sources.</p>
<p>My custom input saves the images id's like this: "11125,11122,11123,11127,11128", so was Pedro said is true it </p>
<blockquote>
<p>is an array with a single string inside</p>
</blockquote>
<p>What I tried next was this:</p>
<pre><code>function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
foreach ( $main_image as $key => $value ) {
$imagesID = explode(',',$value);
foreach ($imagesID as $id => $value) {
$result = wp_get_attachment_url($value);
$custom_fields[ $id ] = $result;
}
};
$image_urls = array();
return $result;
}
</code></pre>
<p>But still no luck, now the "main_image" endpoint appears to be empty.</p>
| [
{
"answer_id": 253282,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 0,
"selected": false,
"text": "<p>based on your comment I think what you need is <code>wp_get_attachment_image_src</code>.</p>\n\n<p>W... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84237/"
] | I'm getting this in my json response
```
"main_image":
[
"11125,11122,11123,11127,11128"
],
```
Those are the ID's of my post, I need to get the URL of each ID in the 'thumbnail' size. I did't find any solution, just this code but It's more for Custom Meta of a plugin.
```
function xxx_past_poss_custom_metadata( $post_response, $post, $context ) {
$meta = get_post_custom( $post['ID'] );
$custom_fields = array();
$xxx_image_gallery = array();
foreach ( $meta['xxx_cmb_image_gallery'] as $key => $value ) {
$value = wp_get_attachment_url($value);
$xxx_image_gallery[ $key ] = $value;
};
foreach ( $meta as $key => $value ) {
// Replace 'xxx_' with any custom metakey prefix (ie. '_' for private metadata's)
if ( 'xxx_' !== substr( $key, 0, 1 ) ) {
$custom_fields[ $key ] = $value;
};
}
$post_response['xxx_image_gallery'] = $xxx_image_gallery;
$post_response['custom_fields'] = $custom_fields;
return $post_response;
}
add_filter( 'json_prepare_post', 'xxx_past_poss_custom_metadata', 10, 3 );
```
My meta it's called "media\_gallery".
Any help will be very appreciated.
[UPDATE]
Seems like I wasn't even modifying my json response because of a plugin I had activated, turning it off made me declare my meta in my functions.php file and no I have this.
```
add_action('rest_api_init', 'register_custom_fields', 1, 1);
function register_custom_fields(){
register_rest_field(
'job_listing',
'thumbnail',
array(
'get_callback' => 'show_image'
)
);
}
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
return $main_image;
}
```
I can now modify the response but I still haven't been able to turn all this ID's: "11125,11122,11123,11127,11128" into URL sources.
My custom input saves the images id's like this: "11125,11122,11123,11127,11128", so was Pedro said is true it
>
> is an array with a single string inside
>
>
>
What I tried next was this:
```
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
foreach ( $main_image as $key => $value ) {
$imagesID = explode(',',$value);
foreach ($imagesID as $id => $value) {
$result = wp_get_attachment_url($value);
$custom_fields[ $id ] = $result;
}
};
$image_urls = array();
return $result;
}
```
But still no luck, now the "main\_image" endpoint appears to be empty. | This is the correct way to achieve it is this:
```
function show_main_image($object, $field_name, $request){
$custom_fields = get_post_custom($object['id']);
$main_image = $custom_fields['main_image'];
$arregloimg = explode(',',$main_image[0]);
$image_urls = array();
foreach ( $arregloimg as $key => $value ) {
$image_urls[] = wp_get_attachment_url($value,'thumbnail');
};
return $image_urls;
}
``` |
253,082 | <p>My site URL in the database shows <code>sitea.com</code>. Is it possible to change this via <code>functions.php</code> into <code>siteb.com</code>, however still maintaining <code>sitea.com</code> in the database? </p>
<p>My current scenario is that I have three developers who work locally and we want to use one database. We all connect to a remote database, however, the URLs from our local development environment and from the remote database are different which causes broken links.</p>
<p>Is there some way to change the <code>siteurl</code> in <code>functions.php</code> while still having the same URL in the database? </p>
<p>Thanks in advance. </p>
| [
{
"answer_id": 253100,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>theme_root_uri</code> filter will allow the URLs returned by <code>get_stylesheet_directory_uri()... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253082",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111250/"
] | My site URL in the database shows `sitea.com`. Is it possible to change this via `functions.php` into `siteb.com`, however still maintaining `sitea.com` in the database?
My current scenario is that I have three developers who work locally and we want to use one database. We all connect to a remote database, however, the URLs from our local development environment and from the remote database are different which causes broken links.
Is there some way to change the `siteurl` in `functions.php` while still having the same URL in the database?
Thanks in advance. | If instead of modifying functions.php you can modify wp-config.php, you can use the following:
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
```
*Source: <https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php>* |
253,092 | <p>I noticed there are plugins to allow shortcode usage in widgets, and they obviously work on posts/pages, but they don't seem to work when added directly to the theme files.</p>
<p>Is there a way to allow shortcodes to work when added to a theme file?</p>
| [
{
"answer_id": 253100,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>theme_root_uri</code> filter will allow the URLs returned by <code>get_stylesheet_directory_uri()... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253092",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94819/"
] | I noticed there are plugins to allow shortcode usage in widgets, and they obviously work on posts/pages, but they don't seem to work when added directly to the theme files.
Is there a way to allow shortcodes to work when added to a theme file? | If instead of modifying functions.php you can modify wp-config.php, you can use the following:
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
```
*Source: <https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php>* |
253,098 | <p>I'm loading posts via Ajax into a div that I have set up on index page.</p>
<p><strong>index page loop:</strong></p>
<pre><code> <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<?php the_post_thumbnail(); ?>
<a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title(); ?></a>
</div>
<?php endwhile; endif; ?>
</code></pre>
<p><strong>Div:</strong></p>
<pre><code><div id="post-container"></div>
</code></pre>
<p><strong>script:</strong></p>
<pre><code><Script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_link = $(this);
$("#post-container").html("loading...");
$("#post-container").load(post_link);
return false;
});
});
</script>
</code></pre>
<p><strong>How to add posts into div with ajax and assign them specific post format?</strong> </p>
| [
{
"answer_id": 253102,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 3,
"selected": true,
"text": "<p>First of all you need to <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253098",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97572/"
] | I'm loading posts via Ajax into a div that I have set up on index page.
**index page loop:**
```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<?php the_post_thumbnail(); ?>
<a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title(); ?></a>
</div>
<?php endwhile; endif; ?>
```
**Div:**
```
<div id="post-container"></div>
```
**script:**
```
<Script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_link = $(this);
$("#post-container").html("loading...");
$("#post-container").load(post_link);
return false;
});
});
</script>
```
**How to add posts into div with ajax and assign them specific post format?** | First of all you need to [register a action callback](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) for you ajax request.
Secondly you need to send all ajax request to `wp-admin/admin-ajax.php` (both `GET` and `POST`).
And lastly you need to modify your javascript a little to pass the `action` parameter which will trigger the callback. and `var post_link = $(this);` doesn't gives the post id from rel attribute you should use `var post_link = $(this).attr("rel");`
You can get the ajax url by `admin_url( 'admin-ajax.php' );` in your theme. and use [javascript localization](https://codex.wordpress.org/Function_Reference/wp_localize_script) to get inside your js.
Everything else looks good on your index.php
**Example**
*JavaScript*
```
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel");
$("#post-container").html("loading...");
//$("#post-container").load(post_link+"?action=load_more_post&pid="+post_id);
// update: .load() should send request to ajax url not the post url
$("#post-container").load(ajax_url+"?action=load_more_post&pid="+post_id);
return false;
});
});
```
*PHP (in your theme's function.php)*
```
add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );
add_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );
function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<h1 class="post_title">'.$post->post_title.'</h1>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}
``` |
253,114 | <p>I was wondering how to achieve this navigation style in WordPress. The menu structure is like this --</p>
<pre><code><ul>
<li>
<a href="index.php">
Home
<span>
MAIN PAGE
</span>
</a>
</li>
</ul>
</code></pre>
<p><a href="https://i.stack.imgur.com/4gSMZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4gSMZ.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 253102,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 3,
"selected": true,
"text": "<p>First of all you need to <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111268/"
] | I was wondering how to achieve this navigation style in WordPress. The menu structure is like this --
```
<ul>
<li>
<a href="index.php">
Home
<span>
MAIN PAGE
</span>
</a>
</li>
</ul>
```
[](https://i.stack.imgur.com/4gSMZ.png) | First of all you need to [register a action callback](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) for you ajax request.
Secondly you need to send all ajax request to `wp-admin/admin-ajax.php` (both `GET` and `POST`).
And lastly you need to modify your javascript a little to pass the `action` parameter which will trigger the callback. and `var post_link = $(this);` doesn't gives the post id from rel attribute you should use `var post_link = $(this).attr("rel");`
You can get the ajax url by `admin_url( 'admin-ajax.php' );` in your theme. and use [javascript localization](https://codex.wordpress.org/Function_Reference/wp_localize_script) to get inside your js.
Everything else looks good on your index.php
**Example**
*JavaScript*
```
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel");
$("#post-container").html("loading...");
//$("#post-container").load(post_link+"?action=load_more_post&pid="+post_id);
// update: .load() should send request to ajax url not the post url
$("#post-container").load(ajax_url+"?action=load_more_post&pid="+post_id);
return false;
});
});
```
*PHP (in your theme's function.php)*
```
add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );
add_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );
function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<h1 class="post_title">'.$post->post_title.'</h1>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}
``` |
253,133 | <p>My current site has custom post types, that run of off the root domain, so anything created inside the CPT will be something like: domain.com/page-name/ rather than domain.com/custom-post-type-name/post-name/. With this, I want to update to WP 4.7 but I cannot because it breaks my website and the CPT's mess up.</p>
<p>Here's why I'm using custom post types, so I have this page template that pulls in everything related to that custom post type and displays those pages a list (similar to the blog page). </p>
<p>However, seeing as everything is of off the root. I was wondering if there was a way to customise Wordpress to give me the option to add a category to a PAGE, therefore, after I can create a code that will display all PAGES within that CATEGORY as a page template.</p>
<p>Reason for this, is will allow me to update to Wordpress 4.7 and not have 5-10 different CPT's as it just gets annoying clicking between the different custom post type labels in the backend.</p>
<p>If anyone has any ideas or know's off a plugin that will do this.</p>
<p>And maybe if some has the code to show all pages as a list, that sit under that category, that would be great - please share.</p>
<p>Thanks.</p>
<p><strong>Update</strong></p>
<p>Here's my code for loop:</p>
<pre><code><?php wp_reset_query(); ?>
<?php $query = new WP_Query( array( post_type=page, 'cat' => 541 ) ); ?>
</code></pre>
have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<p></p>
<pre><code> <?php if(has_post_thumbnail()) {
the_post_thumbnail(array(150,150));
} else {
echo '<img class="alignleft" src="'.get_bloginfo("template_url").'/images/empty_150_150_thumb.gif" width="150" height="150" />';
}
?>
<div class="entry">
<h3 class="blog_header"><a href="<?php echo get_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
<a class="button_link" href="<?php the_permalink(); ?>"><span>Read More</span></a>
</div>
</div>
</code></pre>
<p></p>
<p>I'm attempting to display the pages that have been added to that category within a loop. Is there something wrong with my loop?</p>
<p>Thanks.</p>
| [
{
"answer_id": 253135,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 2,
"selected": false,
"text": "<p>checkout this <a href=\"https://stackoverflow.com/questions/14323582/wordpress-how-to-add-categories-and-... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253133",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98494/"
] | My current site has custom post types, that run of off the root domain, so anything created inside the CPT will be something like: domain.com/page-name/ rather than domain.com/custom-post-type-name/post-name/. With this, I want to update to WP 4.7 but I cannot because it breaks my website and the CPT's mess up.
Here's why I'm using custom post types, so I have this page template that pulls in everything related to that custom post type and displays those pages a list (similar to the blog page).
However, seeing as everything is of off the root. I was wondering if there was a way to customise Wordpress to give me the option to add a category to a PAGE, therefore, after I can create a code that will display all PAGES within that CATEGORY as a page template.
Reason for this, is will allow me to update to Wordpress 4.7 and not have 5-10 different CPT's as it just gets annoying clicking between the different custom post type labels in the backend.
If anyone has any ideas or know's off a plugin that will do this.
And maybe if some has the code to show all pages as a list, that sit under that category, that would be great - please share.
Thanks.
**Update**
Here's my code for loop:
```
<?php wp_reset_query(); ?>
<?php $query = new WP_Query( array( post_type=page, 'cat' => 541 ) ); ?>
```
have\_posts() ) : while ( $query->have\_posts() ) : $query->the\_post(); ?>
```
<?php if(has_post_thumbnail()) {
the_post_thumbnail(array(150,150));
} else {
echo '<img class="alignleft" src="'.get_bloginfo("template_url").'/images/empty_150_150_thumb.gif" width="150" height="150" />';
}
?>
<div class="entry">
<h3 class="blog_header"><a href="<?php echo get_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
<a class="button_link" href="<?php the_permalink(); ?>"><span>Read More</span></a>
</div>
</div>
```
I'm attempting to display the pages that have been added to that category within a loop. Is there something wrong with my loop?
Thanks. | If you don't want to attach the default post category taxonomy, you can always create a new one specifically for pages. Insert this into your `functions.php` file:
```
add_action( 'init', 'create_page_taxonomies' );
function create_page_taxonomies() {
register_taxonomy('page_category', 'page', array(
'hierarchical' => true,
'labels' => array(
'name' => _x( 'Page Category', 'taxonomy general name' ),
'singular_name' => _x( 'page-category', 'taxonomy singular name' ),
'search_items' => __( 'Search Page Categories' ),
'all_items' => __( 'All Page Categories' ),
'parent_item' => __( 'Parent Page Category' ),
'parent_item_colon' => __( 'Parent Page Category:' ),
'edit_item' => __( 'Edit Page Category' ),
'update_item' => __( 'Update Page Category' ),
'add_new_item' => __( 'Add New Page Category' ),
'new_item_name' => __( 'New Page Category Name' ),
'menu_name' => __( 'Page Categories' )
),
'public' => true,
'rewrite' => array(
'slug' => 'page-category',
'with_front' => false,
'hierarchical' => true
)
));
}
```
This is a fairly bare-bones new taxonomy, and there are plenty of other options available, of which there is a complete listing [in the WP Codex](https://codex.wordpress.org/Function_Reference/register_taxonomy).
**UPDATE:**
I believe that this is what the whole loop would look like:
```
<?php
wp_reset_query();
$query = new WP_Query(
array(
'post_type' => 'page',
'tax_query' => array(
array(
'taxonomy' => 'page_category',
'field' => 'term_id',
'terms' => 541
)
)
)
);
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post(); ?>
<div>
<?php
if ( has_post_thumbnail() ) :
the_post_thumbnail( array(150,150) );
else : ?>
<img class="alignleft" src="<?php echo get_bloginfo("template_url"); ?>/images/empty_150_150_thumb.gif" width="150" height="150" />
<?php
endif; ?>
<div class="entry">
<h3 class="blog_header"><a href="<?php echo get_permalink(); ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
<a class="button_link" href="<?php the_permalink(); ?>"><span>Read More</span></a>
</div>
</div>
<?php
endwhile;
endif; ?>
``` |
253,134 | <p>Is there a way to remove "Save draft" button without the use of CSS?</p>
| [
{
"answer_id": 253136,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": -1,
"selected": false,
"text": "<p>Please put the below lines in your wp-config.php </p>\n\n<pre><code>define('WP_POST_REVISIONS', 'false'... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109705/"
] | Is there a way to remove "Save draft" button without the use of CSS? | You cannot just remove the "Save draft" as the button is tied up in the `submitdiv` metabox HTML defined in the function `post_submit_meta_box()`.
However we can alter the callback for this metabox and replace it with our own function.
We can bind to the `submitpost_box` event and give the binding a height weight so it fires last...
```
add_action('submitpost_box', 'my_module_edit_form_after_editor', 100);
```
Then when our action is called we can swap out the metabox callback:
```
function my_module_edit_form_after_editor() {
global $wp_meta_boxes;
$post_type = 'feed';
$context = 'side';
$priority = 'core';
$wp_meta_boxes[$post_type][$context][$priority]['submitdiv']['callback'] = 'my_custom_post_submit_meta_box';
}
```
And then we just need to define what our custom metabox will look like. You could just take the core function `post_submit_meta_box()` and put it into your own plugin removing the unneeded sections, however I would recommend using an actual template and not just closing php tags half way though a function as that just leads to difficult to follow horrible spaghetti code. |
253,144 | <p>I'm fairly new to Wordpress and I'm a little confuse on how to take the database from my local server and replace it with the one on the server on a Wordpress multisite.</p>
<p>I've replace database before from local to server, but it was a multisite.</p>
<p>The step I usually take is:</p>
<ol>
<li>backup the database on the server </li>
<li>export local database </li>
<li>drop all table on the server database </li>
<li>import the local database </li>
<li>go to wp_option </li>
<li>change value for siteurl and home to the site url</li>
</ol>
<p>When I try that, the table on the server is very different from the one on my local.</p>
<p>My local database structure looks like this:</p>
<p><a href="https://i.stack.imgur.com/EDSJo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EDSJo.png" alt="enter image description here"></a></p>
<p>Usually the server database is the same, but not in this case though. </p>
<p>Server database structure:</p>
<p><a href="https://i.stack.imgur.com/5itEC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5itEC.png" alt="enter image description here"></a></p>
<p>So i'm a little confuse on how to tackle this. Can I still do what I usually do, or is there additional steps I need to take?</p>
<p>Thanks in advance.</p>
<p>Edit: Think I overcomplicated this a bit, I could just create a new database on the server and point the wp_config.php file to that instead and everything should be good</p>
<p>Edit 2: nope doesn't work like I thought it would. keep getting redirect loop error</p>
<p>Edit 3: I finally got everything to migrate properly all thanks to <a href="https://wordpress.stackexchange.com/users/9579/michael-ecklund">@Michael Ecklund</a>! Since I was updating the database of the primary page I didn't need to create a new site, but still follow the rest of the <a href="https://wordpress.stackexchange.com/a/253175/101431">instruction</a> he wrote and it went fairly smooth. A bit of confusion at first, but that was my own lack of knowledge.</p>
<p>Edit 4: Just a FYI, if after doing the database migration and you somehow lost access to the dashboard. Go into your main database and in the *_options (in my case the tenp_options) table and look for an <code>wp_user_roles</code> under the option_name column and change that column name to your site prefix (which in my case is <code>tenp_</code>) and you should now be able to access your dashboard again.</p>
| [
{
"answer_id": 253147,
"author": "DGRFDSGN",
"author_id": 108736,
"author_profile": "https://wordpress.stackexchange.com/users/108736",
"pm_score": 1,
"selected": false,
"text": "<p>The database is indeed configured different for a multiwp, those tenp_12 are prefixes for each site in the... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101431/"
] | I'm fairly new to Wordpress and I'm a little confuse on how to take the database from my local server and replace it with the one on the server on a Wordpress multisite.
I've replace database before from local to server, but it was a multisite.
The step I usually take is:
1. backup the database on the server
2. export local database
3. drop all table on the server database
4. import the local database
5. go to wp\_option
6. change value for siteurl and home to the site url
When I try that, the table on the server is very different from the one on my local.
My local database structure looks like this:
[](https://i.stack.imgur.com/EDSJo.png)
Usually the server database is the same, but not in this case though.
Server database structure:
[](https://i.stack.imgur.com/5itEC.png)
So i'm a little confuse on how to tackle this. Can I still do what I usually do, or is there additional steps I need to take?
Thanks in advance.
Edit: Think I overcomplicated this a bit, I could just create a new database on the server and point the wp\_config.php file to that instead and everything should be good
Edit 2: nope doesn't work like I thought it would. keep getting redirect loop error
Edit 3: I finally got everything to migrate properly all thanks to [@Michael Ecklund](https://wordpress.stackexchange.com/users/9579/michael-ecklund)! Since I was updating the database of the primary page I didn't need to create a new site, but still follow the rest of the [instruction](https://wordpress.stackexchange.com/a/253175/101431) he wrote and it went fairly smooth. A bit of confusion at first, but that was my own lack of knowledge.
Edit 4: Just a FYI, if after doing the database migration and you somehow lost access to the dashboard. Go into your main database and in the \*\_options (in my case the tenp\_options) table and look for an `wp_user_roles` under the option\_name column and change that column name to your site prefix (which in my case is `tenp_`) and you should now be able to access your dashboard again. | Merging WordPress Standalone Installation with WordPress Multisite Installation
-------------------------------------------------------------------------------
**Before You Begin:**
1. Create a new site in your Multisite Network, which will be the site
you're migrating from the Standalone installation. (Take note of the site ID #, you'll need it later.)
2. You need to make sure that all of the users from the Standalone
installation, are created and exist in the Multisite installation.
Step 1 - Backup Databases.
--------------------------
Find the directory on your Web Server which the the Standalone copy of WordPress is installed and the directory on your Web Server which the Multisite copy of WordPress is installed and open the `wp-config.php` file of both installations. Locate the PHP constant `DB_NAME`. It contains the name of the database that particular installation of WordPress is using.
1. Backup the Standalone instillation's database.
2. Backup the Multisite installation's database.
Step 2 - Identify the Database Table Prefixes.
----------------------------------------------
*By default the database table prefix is `wp_`.*
If you can't identify the database table prefix just by examining the database. You can look in the base directory of your WordPress installation and open the `wp-config.php` file of the site in question and look for a line like `$table_prefix = 'wp_';`.
**In your situation, it looks like:**
* The Standalone installation's database table prefix is the default of
`wp_`.
* The Multisite installation's database table prefix is custom of
`tenp_`.
Step 3 - Export Databases. Import Into Local Environment.
---------------------------------------------------------
On a local Database Server, create a temporary database for each of these databases. Perhaps to keep things simple, label one database "`standalone`", and the second one "`multisite`".
* Import the Standalone installation's database (which you just
exported) into the "`standalone`" database (which you just created) on
your local Database Server.
* Import the Multisite installation's database (which you just
exported) into the "`multisite`" database (which you just created) on
your local Database Server.
Step 4 - Search and Replace.
----------------------------
This is the step where you would likely replace any necessary URL changes. (http to https), (non-www to www), (add or remove directories from URL), etc.
Perform this task on the "`standalone`" database you created on your local Database Server.
Remember to change things to how you would like them to be in the Multisite installation (the end result).
**For this procedure, you're going to need a Database Tool:**
1. [WP-CLI :: wp search-replace](http://wp-cli.org/commands/search-replace/) which is
all command line.
2. Alternatively, if you prefer a GUI, there's the [Database Search and
Replace Script in PHP by
interconnect/it](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/).
**Step 4.2 - Users and Post Authors**
You'll want to probably create a note about all the user's from your Standalone installation and map the old user ID's to the new user ID's (from the Multisite installation).
You can simply just create a temporary text file and do something like this:
```
1 => 4
8 => 23
15 => 9
```
The numbers on the left are the ID's from the Standalone installation and the numbers on the right are the ID's on the Multisite installation.
You'll then want to update the `post_author` column of the `wp_posts` table to update all of the old user ID's to the new user ID's. Otherwise when view your migrated site from Standalone to Multisite, you're going to be one confused kitten. It's going to say things on your site were posted by random people and probably even people from different sites in your network. This can be catastrophic if overlooked.
For each of the user ID mappings in your text file, you'll want to issue a command much like this into MySQL:
```
UPDATE wp_posts
SET post_author = '4'
WHERE post_author = '1'
```
* The line `SET post_author = '4'` is the new user ID (the user ID from
the Multisite installation)
* The line `WHERE post_author = '1'` is the old user ID (the user ID
from the Standalone installation)
Step 5 - Users and Usermeta
---------------------------
I haven't really found a good solution for this step yet. I usually just recreate the users manually in the Multisite installation.
In otherwords, I usually just drop two tables `wp_users` and `wp_usermeta`.
*If anyone would like to improve on this step feel free to edit and add guidance here.*
Step 6 - Update Database Table Names
------------------------------------
This step is much like Step 4.
You'll want to map old table names to new table names in the "`standalone`" database on your local Database Server.
This is the step where you will need to know the site ID # from your Multisite installation.
**As an example:** If your site ID is `15`, and your database table prefix use on your Multisite installation is `tenp_`, then the database table `wp_posts` would become `tenp_15_posts`.
Here's the MySQL command you can use to update your database table names:
```
RENAME TABLE `wp_posts`
TO `tenp_15_posts`;
```
* The first line is the old database table name (the database table name from the Standalone installation)
* The second line is the new database table name (the database table name format to be used in the Multisite installation)
Alternatively, if your database is small enough. You could just export the entire database and open it in a text editor. Then find all & replace. Save it when completed.
Step 7 - Export and Import
--------------------------
Once all of the above changes have been made, export the "`standalone`" database from your local Database Server.
1. Import the exported `.sql` file into the "`multisite`" database on
your local Database Server.
2. Export the "`multisite`" database from your local Database Server.
3. Drop the current Multisite database tables used for your existing
Multisite database (not the one on your local Database Server).
4. Import the `.sql` file for your "`multisite`" database you exported
from your local Database Server and import it to your database used
by your existing Multisite installation (the one you just dropped
all the tables from). Essentially just replacing the current
Multisite installation's database with the modified one which
contains the newly migrated Standalone site.
---
**Moving Uploads files from `./wp-content/`.**
Standalone and Multisite store uploaded files differently. Multisite stores them in `./wp-content/sites/{$site_id}/`. Make sure you move your uploaded files appropriately as well.
---
**Changing the Primary Site:**
Look for database table `wp_site` in your Multisite database. Edit the column `id` and `domain` appropriately.
You might need to also edit the `site_id` column in the `wp_blogs` table.
Also look in `wp-config.php` for these lines and once again, adjust them accordingly.
```
define( 'DOMAIN_CURRENT_SITE', 'www.your-domain.com' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );
```
---
**Useful Links:**
* [Moving WordPress](https://codex.wordpress.org/Moving_WordPress)
* [Migrating Multiple Blogs into WordPress 3.0
Multisite](https://codex.wordpress.org/Migrating_Multiple_Blogs_into_WordPress_3.0_Multisite)
---
**End.**
**If anything is confusing, please comment and I'll try to clear it up.** |
253,155 | <p>How do I fit a function inside an opening and closing shortcode.</p>
<p>I have this function that displays the post's pdf attachment url</p>
<pre><code>$file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id );
printf( '%s', $full_size); } }
</code></pre>
<p>How would I fit the above code into this...</p>
<pre><code>echo do_shortcode( '[pdf]' . $text_to_be_wrapped_in_shortcode . '[/pdf]' );
</code></pre>
| [
{
"answer_id": 253159,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 0,
"selected": false,
"text": "<p>Worked it out...</p>\n\n<pre><code><?php $file= get_post_meta( $post->ID, 'teacher-resume-upload' ); $full... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] | How do I fit a function inside an opening and closing shortcode.
I have this function that displays the post's pdf attachment url
```
$file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id );
printf( '%s', $full_size); } }
```
How would I fit the above code into this...
```
echo do_shortcode( '[pdf]' . $text_to_be_wrapped_in_shortcode . '[/pdf]' );
``` | This should work assuming your trying to pass the URL to the PDF short code
```
$file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) {
foreach ( $file as $attachment_id ) {
$full_size = wp_get_attachment_url( $attachment_id );
echo do_shortcode( '[pdf]' . $full_size . '[/pdf]' );
}
}
``` |
253,216 | <p>how can I create non-Wordpress sites on subdomains (map them to directories), when I have an active subdomain-multisite WP installation?</p>
<p>Can I insert some .. exemptions into htaccess or something?</p>
| [
{
"answer_id": 266673,
"author": "Karthik",
"author_id": 68260,
"author_profile": "https://wordpress.stackexchange.com/users/68260",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. We can add rewrite rule in WordPress root <code>.htaccess</code> to rewrite all requests for a particula... | 2017/01/19 | [
"https://wordpress.stackexchange.com/questions/253216",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38435/"
] | how can I create non-Wordpress sites on subdomains (map them to directories), when I have an active subdomain-multisite WP installation?
Can I insert some .. exemptions into htaccess or something? | The [WP Codex gives two examples of excluding a subdirectory from multisite's control.](https://codex.wordpress.org/WPMS_Ignore_Some_Subdomains)
1. .htaccess method [(as Karthik noted)](https://wordpress.stackexchange.com/a/266673/118366)
2. Virtual host method
.htaccess
---------
Being sure to call the sub rewrite BEFORE the rewrite of ww.domain.com to domain.com
```
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} subdomain.domain.com
RewriteCond %{REQUEST_URI} !subdomain/
RewriteRule ^(.*)$ subdomain/$1 [L]
# Rewrite http://www.domain.com to domain.com
RewriteCond %{HTTP_HOST} ^www.(.*)
RewriteRule ^(.*) http://%1/$1 [R,L]
```
This answer to issues with this covers the hierarchical nature of .htaccess to keep in mind: <https://wordpress.stackexchange.com/a/20274/118366>
Virtual Host
------------
Quoting the linked Codex page on this:
>
> If you are able to configure your VirtualHost file this may be the best method. It provides the ability to serve the subdomain out of any directory on your server.
>
>
> To do this you simply need to make sure that the domain you do not want WPMS to handle is loaded before the WPMS primary domain that uses the wildcard.
>
>
> |
253,226 | <p>I have an attachment page for post images, so that when I click on the thumbnail (on the front end) it takes the user to the attachment page for that image, how would I do the same for pdf files, so that when I click on the direct link to the pdf on the front end to redirects to the pdf attachment page?</p>
<pre><code><?php if ( wp_attachment_is_image( $post->id ) ) : $att_image = wp_get_attachment_image_src( $post->id, "full"); ?>
<center>
<p class="full-attachment">
<?php /* <a href="<?php echo wp_get_attachment_url($post->id); ?>" title="<?php the_title(); ?>" rel="attachment"> */ ?>
<img src="<?php echo $att_image[0];?>" width="<?php echo $att_image[1];?>" height="<?php echo $att_image[2];?>" class="attachment-full" alt="<?php $post->post_title; ?>" />
<?php /* </a> */ ?>
</p>
</center>
<?php else : ?>
<a href="<?php echo wp_get_attachment_url($post->ID) ?>" title="<?php echo wp_specialchars( get_the_title($post->ID), 1 ) ?>" rel="attachment">
<?php echo basename($post->guid) ?>
</a>
<?php endif; ?>
</code></pre>
<p>This is my theme file's single.php</p>
<pre><code><?php $file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id ); printf( '<a href="%s">download</a>', $full_size); } } ?>
</code></pre>
| [
{
"answer_id": 253291,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>From the <a href=\"https://developer.wordpress.org/reference/functions/get_attachment_template/\" rel=\"nofol... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] | I have an attachment page for post images, so that when I click on the thumbnail (on the front end) it takes the user to the attachment page for that image, how would I do the same for pdf files, so that when I click on the direct link to the pdf on the front end to redirects to the pdf attachment page?
```
<?php if ( wp_attachment_is_image( $post->id ) ) : $att_image = wp_get_attachment_image_src( $post->id, "full"); ?>
<center>
<p class="full-attachment">
<?php /* <a href="<?php echo wp_get_attachment_url($post->id); ?>" title="<?php the_title(); ?>" rel="attachment"> */ ?>
<img src="<?php echo $att_image[0];?>" width="<?php echo $att_image[1];?>" height="<?php echo $att_image[2];?>" class="attachment-full" alt="<?php $post->post_title; ?>" />
<?php /* </a> */ ?>
</p>
</center>
<?php else : ?>
<a href="<?php echo wp_get_attachment_url($post->ID) ?>" title="<?php echo wp_specialchars( get_the_title($post->ID), 1 ) ?>" rel="attachment">
<?php echo basename($post->guid) ?>
</a>
<?php endif; ?>
```
This is my theme file's single.php
```
<?php $file= get_post_meta( $post->ID, 'teacher-resume-upload' );
if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id ); printf( '<a href="%s">download</a>', $full_size); } } ?>
``` | You can use `pdf.php` or a number of other specially-named template files [as described birgire's answer](https://wordpress.stackexchange.com/a/253291/8559) to show an attachment page specifically for PDFs, or use a generic `attachment.php` page that includes conditional statements for the type of attachment (like the code in your question does).
Potential Conflict with Yoast SEO Plugin
----------------------------------------
Note that attachment template pages may not work if you have the Yoast SEO plugin installed. The default setting under **Yoast SEO › Search Appearance › Media** is to 'Redirect attachment URLs to the attachment itself,' which will override any attachment page template and directly link to the PDF, image file, or whatever you've uploaded.
How to Use Attachment Page Only for PDFs and Redirect Other Attachment Types Directly to their Files
----------------------------------------------------------------------------------------------------
Bonus: If you *only* want to show PDF attachment pages and redirect everything else to the attachment file, here's some code to do that. (You'd put this in your `functions.php` file.)
```php
/**
* Redirect media attachment URLs to the attachment itself *unless* it's a PDF.
* See details: https://wordpress.stackexchange.com/questions/253226/
*/
add_action(
'template_redirect',
function() {
// Exit if this is not an attachment page.
if ( ! is_attachment() ) {
return;
}
// Exit (do nothing; do not redirect; use
// the pdf.php attachment template page)
// if this is a PDF attachment page.
if ( false !== stripos( get_post_mime_type(), 'pdf' ) ) {
return;
}
// Redirect all other attachment pages to
// their file. Use code '301' to indicate
// this is a permanent redirect.
if ( wp_get_attachment_url() ) {
wp_safe_redirect( wp_get_attachment_url(), '301' );
}
}
);
``` |
253,235 | <p>I am trying to display the numerical post order ranking on the home page, however, I am using template_parts and am not aware of how to do this when the html is separated from the wordpress loop.</p>
<p>Here's what I want to see:</p>
<p><a href="https://i.stack.imgur.com/bO3EC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bO3EC.png" alt="ranking concept"></a></p>
<p>Here is my loop in <code>index.php</code></p>
<pre><code><div class="most-recent-feed">
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
$post_ranking = 1;
/* Start the Loop */
while ( have_posts() ) : the_post();
?> <h1> <?php echo $post_ranking ?> </h1> <?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( 'template-parts/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
wp_reset_query();
?>
</div>
</code></pre>
<p>And here is my relevant html in <code>template_parts/content.php</code> (note the comment where the ranking number should be placed:</p>
<pre><code><div class="album-dark-overlay play">
<div class="ranking-triangle">
<!-- Ranking number should be placed here -->
</div>
<div id="<?php echo $youtube_id ?>" data-youtube-id="<?php echo $youtube_id ?>" class="media-circle">
<i class="icon ion-ios-play"></i><i class="icon ion-pause"></i>
</div>
</div>
</code></pre>
| [
{
"answer_id": 253242,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>There are two ways I suggest you do that:</p>\n\n<ul>\n<li>You can store the post rankings in your datab... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105532/"
] | I am trying to display the numerical post order ranking on the home page, however, I am using template\_parts and am not aware of how to do this when the html is separated from the wordpress loop.
Here's what I want to see:
[](https://i.stack.imgur.com/bO3EC.png)
Here is my loop in `index.php`
```
<div class="most-recent-feed">
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
$post_ranking = 1;
/* Start the Loop */
while ( have_posts() ) : the_post();
?> <h1> <?php echo $post_ranking ?> </h1> <?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( 'template-parts/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
wp_reset_query();
?>
</div>
```
And here is my relevant html in `template_parts/content.php` (note the comment where the ranking number should be placed:
```
<div class="album-dark-overlay play">
<div class="ranking-triangle">
<!-- Ranking number should be placed here -->
</div>
<div id="<?php echo $youtube_id ?>" data-youtube-id="<?php echo $youtube_id ?>" class="media-circle">
<i class="icon ion-ios-play"></i><i class="icon ion-pause"></i>
</div>
</div>
``` | It is not straightforward to pass a variable to a template part. However, when you are in a loop, WP has [a counter called `current_post`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties) that you can use in this way in your template part:
```
global $post;
$ranking = $post->$current_post + 1; // +1 because the counter starts at 0
``` |
253,239 | <p>I would like to make my pagination for single post look like this:</p>
<p><a href="https://i.stack.imgur.com/f2kJe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f2kJe.jpg" alt="pagination with next, prev and links in between and also disabled"></a></p>
<p>and <strong>not</strong> like that.....
<a href="https://i.stack.imgur.com/PCSlu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PCSlu.jpg" alt="current pagination"></a></p>
<p>I am using wordpress and for pagination in single post i using the quicktag. Theme is MH Magazine liteVersion: 2.5.3</p>
| [
{
"answer_id": 253242,
"author": "Samuel Asor",
"author_id": 84265,
"author_profile": "https://wordpress.stackexchange.com/users/84265",
"pm_score": -1,
"selected": false,
"text": "<p>There are two ways I suggest you do that:</p>\n\n<ul>\n<li>You can store the post rankings in your datab... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253239",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111342/"
] | I would like to make my pagination for single post look like this:
[](https://i.stack.imgur.com/f2kJe.jpg)
and **not** like that.....
[](https://i.stack.imgur.com/PCSlu.jpg)
I am using wordpress and for pagination in single post i using the quicktag. Theme is MH Magazine liteVersion: 2.5.3 | It is not straightforward to pass a variable to a template part. However, when you are in a loop, WP has [a counter called `current_post`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties) that you can use in this way in your template part:
```
global $post;
$ranking = $post->$current_post + 1; // +1 because the counter starts at 0
``` |
253,245 | <p>I just migrated my ecommerce website (www.getfitkart.com) from shared hosting to Linode. Now only the home page is working but the other pages are not getting served. I am getting the following error on all other pages like say, <a href="http://www.getfitkart.com/privacy-policy/" rel="noreferrer">http://www.getfitkart.com/privacy-policy/</a></p>
<blockquote>
<p>Not Found<br/>
The requested URL /privacy-policy/ was not found on this server.</p>
</blockquote>
<p>My .htaccess file:<br/></p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code></pre>
<p>Any help will be greatly appreciated.</p>
| [
{
"answer_id": 253246,
"author": "Umer Shoukat",
"author_id": 94940,
"author_profile": "https://wordpress.stackexchange.com/users/94940",
"pm_score": 4,
"selected": false,
"text": "<p>Go to settings->permalinks and click on save button to rewrite flush. And then empty your browser cache... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253245",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43567/"
] | I just migrated my ecommerce website (www.getfitkart.com) from shared hosting to Linode. Now only the home page is working but the other pages are not getting served. I am getting the following error on all other pages like say, <http://www.getfitkart.com/privacy-policy/>
>
> Not Found
>
> The requested URL /privacy-policy/ was not found on this server.
>
>
>
My .htaccess file:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
Any help will be greatly appreciated. | I found the solution here:
<https://www.digitalocean.com/community/questions/wordpress-permalinks-not-working-on-ubuntu-14-04>
The thing is that we need to allow the override *all* option in httpd.conf (location: /etc/httpd/conf/httpd.conf) for your specific hosting directory. |
253,270 | <p>I have a lot of 404s on posts without /%category%/ (I have change permalink structure). I have noticed that if I put /anything/ in 404 link as category I'll end up in the right post.
How can I solve it? I have around 25k 404s in google console and I need a bulk solution. </p>
<p>My thoughts are either to do it in htaccess or in 404.php (preferably). I was thinking to check request in 404.php and if it misses /category/ just to insert any word and make a new request toward WP to resolve the post.</p>
<p>Any thoughts?</p>
| [
{
"answer_id": 253271,
"author": "Ravi Shinde",
"author_id": 99294,
"author_profile": "https://wordpress.stackexchange.com/users/99294",
"pm_score": 0,
"selected": false,
"text": "<p>Use Redirection plugin - <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253270",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78008/"
] | I have a lot of 404s on posts without /%category%/ (I have change permalink structure). I have noticed that if I put /anything/ in 404 link as category I'll end up in the right post.
How can I solve it? I have around 25k 404s in google console and I need a bulk solution.
My thoughts are either to do it in htaccess or in 404.php (preferably). I was thinking to check request in 404.php and if it misses /category/ just to insert any word and make a new request toward WP to resolve the post.
Any thoughts? | Ok, resolved it in 404.php
```
<?php
$klo_link = $_SERVER['REQUEST_URI'];
if (preg_match("/^\/[a-zA-Z0-9\-\_]+\/$/", $klo_link)) {
//echo "A match was found. \n";
//echo $klo_link;
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url')."/a".$klo_link);
exit();
}else {
get_header();
}
```
Put that at the beginning of the 404.ph |
253,274 | <p>I'm seeing an error while trying to change the colours of a theme:</p>
<pre><code>Notice: Use of undefined constant FS_CHMOD_DIR - assumed 'FS_CHMOD_DIR' in
/var/www/vhosts/xxx/wp-content/themes/consulting/inc/print_styles.php on line 141
</code></pre>
<p>The theme creator has given me the following advice, but cannot provide any further detail:</p>
<blockquote>
<p>Please contact your hosting provider team and ask to enable (set up)
PHP FILE extension in your site. It will solve the problem.</p>
</blockquote>
<p>I manage my server, but I have also been in contact with my hosting provider, and neither of us can figure out what needs to be done.</p>
<p>the closest we can find to PHP FILE is the fileinfo extension, which is already installed:</p>
<pre><code>[root]# php -m | grep file
fileinfo
</code></pre>
<p>Can anyone shed any light on this?</p>
| [
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253274",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111367/"
] | I'm seeing an error while trying to change the colours of a theme:
```
Notice: Use of undefined constant FS_CHMOD_DIR - assumed 'FS_CHMOD_DIR' in
/var/www/vhosts/xxx/wp-content/themes/consulting/inc/print_styles.php on line 141
```
The theme creator has given me the following advice, but cannot provide any further detail:
>
> Please contact your hosting provider team and ask to enable (set up)
> PHP FILE extension in your site. It will solve the problem.
>
>
>
I manage my server, but I have also been in contact with my hosting provider, and neither of us can figure out what needs to be done.
the closest we can find to PHP FILE is the fileinfo extension, which is already installed:
```
[root]# php -m | grep file
fileinfo
```
Can anyone shed any light on this? | It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder ) |
253,278 | <p>When user created URL comes as <strong>www.sitename.com/user/username</strong></p>
<p>I want to change to<br>
<strong>www.sitename.com/username</strong> (Remove User from URL)</p>
<p>How can I do this </p>
| [
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253278",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111277/"
] | When user created URL comes as **www.sitename.com/user/username**
I want to change to
**www.sitename.com/username** (Remove User from URL)
How can I do this | It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder ) |
253,283 | <p>when i install a theme it appears to be completely different and doenst shows contents which are supposed to be there. And nothing happens if a do changes from dashboard appearance and customize. kindly help!
[![see here][1]][1]</p>
<p>[![?][2]][2]</p>
<p><a href="https://i.stack.imgur.com/6MQE4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6MQE4.png" alt="?"></a></p>
<p><a href="https://i.stack.imgur.com/WmLxB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WmLxB.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253283",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111374/"
] | when i install a theme it appears to be completely different and doenst shows contents which are supposed to be there. And nothing happens if a do changes from dashboard appearance and customize. kindly help!
[![see here][1]][1]
[![?][2]][2]
[](https://i.stack.imgur.com/6MQE4.png)
[](https://i.stack.imgur.com/WmLxB.png) | It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder ) |
253,290 | <p>I have this php file on the root directory, and i seen this example for inserting post from external php file
but for some reason it doesn't work for me, <code>wp_insert_post()</code> always returns <code>0</code></p>
<p>So whats the problem ? and how i can fix it?</p>
<p>I'm trying to build a Cron Job file to insert new posts from XML file In the end</p>
<p>Thank you!</p>
<p>CronJob.php:</p>
<pre><code><?php
require_once './wp-load.php';
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => '3',
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
var_dump($post_id); die; // Return int(0)
</code></pre>
| [
{
"answer_id": 253277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>It's really quite simple. The theme author is using a constant that you can put in <code>wp-config.php</code>... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253290",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110929/"
] | I have this php file on the root directory, and i seen this example for inserting post from external php file
but for some reason it doesn't work for me, `wp_insert_post()` always returns `0`
So whats the problem ? and how i can fix it?
I'm trying to build a Cron Job file to insert new posts from XML file In the end
Thank you!
CronJob.php:
```
<?php
require_once './wp-load.php';
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => '3',
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
var_dump($post_id); die; // Return int(0)
``` | It's really quite simple. The theme author is using a constant that you can put in `wp-config.php`, but because you don't use that constant, and the author never checks if it's actually defined, the code throws a PHP warning
<https://codex.wordpress.org/Editing_wp-config.php#Override_of_default_file_permissions>
>
> ### Override of default file permissions
>
>
> The FS\_CHMOD\_DIR and
> FS\_CHMOD\_FILE define statements allow override of default file
> permissions. These two variables were developed in response to the
> problem of the core update function failing with hosts running under
> suexec. If a host uses restrictive file permissions (e.g. 400) for all
> user files, and refuses to access files which have group or world
> permissions set, these definitions could solve the problem. Note that
> the '0755' is an octal value. Octal values must be prefixed with a 0
> and are not delineated with single quotes ('). See Also: Changing File
> Permissions
>
>
>
FAQ
---
### So Who's to Blame?
The theme author for not checking if a constant is defined before using it. I've never needed this constant and i've worked on a lot of sites, and from the sounds of it neither have you.
The check is an easy thing to do:
```
$chmod_dir = ( 0755 & ~ umask() );
if ( defined( 'FS_CHMOD_DIR' ) ) {
$chmod_dir = FS_CHMOD_DIR;
}
```
You use a variable, give it a default variable, then assign the constant to it if it exists.
### What about this file PHP extension?
It's BS, a red herring, my guess is you've either been fobbed off, or the developer has made a guess, probably the latter. The constant is a WordPress constant, and you should never rely on all constants being defined ( they're mostly optional after all )
### Is all of this above board?
Why would your theme need the chmod files and folders? This all sounds very suspicious, themes shouldn't be writing to the disk, especially on the frontend. That's how sites fail to scale or slow down.
I would cast a sceptical eye on the theme, it sounds from the file name like the theme is generating files and saving them in a subfolder, a massive no no, afterall there's a set of APIs for writing to the uploads folder, and you can generate and return a cacheable CSS file via PHP and rewrite rules ( there are security consequences too if you have a writable theme folder ) |
253,315 | <p>Looks like WordPress unnecessarily fire WP CRON on every page load. I'm thinking, instead of having it run on every visit, why not just schedule it to run every 5 minutes via server? I could simply trigger wp-cron.php every five minutes and achieve desired result?</p>
<p>Is there any downside to this? </p>
| [
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER v... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21100/"
] | Looks like WordPress unnecessarily fire WP CRON on every page load. I'm thinking, instead of having it run on every visit, why not just schedule it to run every 5 minutes via server? I could simply trigger wp-cron.php every five minutes and achieve desired result?
Is there any downside to this? | There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features. |
253,316 | <p>I just reinstalled Wordpress to fix another problem. I followed careful instructions about backing up my database but now I get error 1062 from mySQL when I try to reinstall the database. This is because a duplicate database seems to have been created, stopping me uploading my saved version.</p>
<p>How can I delete/override the duplicate database? </p>
<p>Thanks</p>
| [
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER v... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253316",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110850/"
] | I just reinstalled Wordpress to fix another problem. I followed careful instructions about backing up my database but now I get error 1062 from mySQL when I try to reinstall the database. This is because a duplicate database seems to have been created, stopping me uploading my saved version.
How can I delete/override the duplicate database?
Thanks | There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features. |
253,333 | <p>I have a search page that when you enter a blank query, it shows posts and pages together. This isn't an issue, it's fine. However I'd like to remove some details like the date from the pages as it doesn't make much sense.</p>
<p>I'm using the is_page function but that doesn't seem to work and I have no idea why, I'm including all of the necessary information (or so I thought).</p>
<pre><code><?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>">
<?php if ( is_page() ) : ?>
<?php the_title(); ?>
<?php else : ?>
<?php the_title(); ?>
<?php the_time("jS F Y"); ?>
<?php foreach ( get_the_category() as $the_category ) : ?>
<?php echo $the_category->cat_name; ?>
<?php endforeach; ?>
<?php endif; ?>
</article>
<?php endwhile; ?>
</code></pre>
<p>The <a href="https://developer.wordpress.org/reference/functions/is_page/" rel="nofollow noreferrer">is_page</a> function in the WP Codex.</p>
| [
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER v... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253333",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have a search page that when you enter a blank query, it shows posts and pages together. This isn't an issue, it's fine. However I'd like to remove some details like the date from the pages as it doesn't make much sense.
I'm using the is\_page function but that doesn't seem to work and I have no idea why, I'm including all of the necessary information (or so I thought).
```
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>">
<?php if ( is_page() ) : ?>
<?php the_title(); ?>
<?php else : ?>
<?php the_title(); ?>
<?php the_time("jS F Y"); ?>
<?php foreach ( get_the_category() as $the_category ) : ?>
<?php echo $the_category->cat_name; ?>
<?php endforeach; ?>
<?php endif; ?>
</article>
<?php endwhile; ?>
```
The [is\_page](https://developer.wordpress.org/reference/functions/is_page/) function in the WP Codex. | There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features. |
253,344 | <p>I dont want to show image in my read_more function in homepage. read_more shows first 25 strings of my content. when I add image in the content it shows with the string inline. I don't want the image. Anyone know how to do it? here is my code below..</p>
<pre><code><div id="leadnewsbox" class="col-md-5 col-sm-4 col-xs-12">
<?php
$breakingcat = get_the_category_by_id($btimes['breaking-news-category']);
$breakingnews = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => $breakingcat
));
while($breakingnews->have_posts()) : $breakingnews->the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('post-image'); ?></a>
<div class="leadnewsboxtitle">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php read_more(25); ?>...</p>
</div>
<?php endwhile; ?>
</code></pre>
<p></p>
<pre><code>// read_more function
function read_more($limit){
$content = explode(' ', get_the_content());
$less_content = array_slice($content, 0 , $limit);
echo implode (' ', $less_content);
}
</code></pre>
| [
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER v... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253344",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111404/"
] | I dont want to show image in my read\_more function in homepage. read\_more shows first 25 strings of my content. when I add image in the content it shows with the string inline. I don't want the image. Anyone know how to do it? here is my code below..
```
<div id="leadnewsbox" class="col-md-5 col-sm-4 col-xs-12">
<?php
$breakingcat = get_the_category_by_id($btimes['breaking-news-category']);
$breakingnews = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => $breakingcat
));
while($breakingnews->have_posts()) : $breakingnews->the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('post-image'); ?></a>
<div class="leadnewsboxtitle">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php read_more(25); ?>...</p>
</div>
<?php endwhile; ?>
```
```
// read_more function
function read_more($limit){
$content = explode(' ', get_the_content());
$less_content = array_slice($content, 0 , $limit);
echo implode (' ', $less_content);
}
``` | There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features. |
253,351 | <p>Hi I am new to Wordpress development and I have learned a lot already but I do not understand why the text and content in the pages and posts does not keep the format that the user sets in the back-end editor for posts or pages. And everything looks like a mess, formatting goes wild and it does not resemble the editor version at all. What am I missing in my code? I don't understand what is wrong, is it my css rules? </p>
<p>A funny thing is that when I change to another theme, the formatting does remain in place. And it seems to work with any theme available in the wordpress themes section.</p>
<p>Please help. </p>
| [
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER v... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253351",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106353/"
] | Hi I am new to Wordpress development and I have learned a lot already but I do not understand why the text and content in the pages and posts does not keep the format that the user sets in the back-end editor for posts or pages. And everything looks like a mess, formatting goes wild and it does not resemble the editor version at all. What am I missing in my code? I don't understand what is wrong, is it my css rules?
A funny thing is that when I change to another theme, the formatting does remain in place. And it seems to work with any theme available in the wordpress themes section.
Please help. | There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features. |
253,353 | <p>I'm looking for help on how to add specific menu on a specific page or pages with no plugin.</p>
<p>I know how to add and register a new menu like this:</p>
<pre><code>//* Register third navigation menu position
function register_additional_menu() {
register_nav_menu( 'third-menu' ,__( 'Third Navigation Menu' ));
}
add_action( 'init', 'register_additional_menu' );
add_action( 'genesis_before_content', 'add_third_nav_genesis' );
function add_third_nav_genesis() {
echo'<div class="osastot-valikko">';
wp_nav_menu( array( 'theme_location' => 'third-menu', 'container_class' => 'genesis-nav-menu js-superfish sf-js-enabled sf-arrows' ) );
echo'</div>';
}
</code></pre>
<p>I would like to have a navigation menu named "Extra Menu" displayed only on three pages (post=6, post=7, post=8). What should I write in my function.php</p>
<p>Thanks!</p>
| [
{
"answer_id": 253329,
"author": "TechnicalChaos",
"author_id": 111398,
"author_profile": "https://wordpress.stackexchange.com/users/111398",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of downsides:\nFirstly, when using wp-cron.php as a cli things such as $_SERVER v... | 2017/01/20 | [
"https://wordpress.stackexchange.com/questions/253353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111269/"
] | I'm looking for help on how to add specific menu on a specific page or pages with no plugin.
I know how to add and register a new menu like this:
```
//* Register third navigation menu position
function register_additional_menu() {
register_nav_menu( 'third-menu' ,__( 'Third Navigation Menu' ));
}
add_action( 'init', 'register_additional_menu' );
add_action( 'genesis_before_content', 'add_third_nav_genesis' );
function add_third_nav_genesis() {
echo'<div class="osastot-valikko">';
wp_nav_menu( array( 'theme_location' => 'third-menu', 'container_class' => 'genesis-nav-menu js-superfish sf-js-enabled sf-arrows' ) );
echo'</div>';
}
```
I would like to have a navigation menu named "Extra Menu" displayed only on three pages (post=6, post=7, post=8). What should I write in my function.php
Thanks! | There is no downside for running WP CRON using the server's cron jobs. In fact this is the recommended practice.
According to [Official WordPress Plugin Development Document](https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/):
>
> WP-Cron does not run continuously, which can be an issue if there are critical tasks that must run on time. There is an easy solution for this. Simply set up your system’s task scheduler to run on the intervals you desire (or at the specific time needed).
>
>
>
To do this, you need to first disable the default cron behaviour in `wp-config.php`:
```
define('DISABLE_WP_CRON', true);
```
Then, schedule `wp-cron.php` from your server. For Linux, that means:
```
crontab -e
```
However, instead of running it in Command Line (CLI), run it as an HTTP request. For that you may use `wget`:
```
*/5 * * * * wget -q -O - https://your-domain.com/wp-cron.php?doing_wp_cron
```
WordPress loads all the required core files, Plugins etc. in `wp-cron.php` with the following CODE:
```
if ( !defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
```
So don't worry about WordPress not loading important features. |
253,385 | <p>Goal: convert Facebook url itself (without full code snippet) into Facebook post on website front-end</p>
<p>Problem: The experimental o2 / p2 / breathe theme, by default, converts a full Facebook code snippet in the editor to a full Facebook post on the front-end. Example snippet:</p>
<pre><code><div class="fb-post" data-href="https://www.facebook.com/WordPresscom/posts/10154113693553980" max-width="90%">
</code></pre>
<p>I would like to instead just be able to post ONLY the url into the editor and have the url wrapped with <code><div class="fb-post" data-href=" ... " max-width="90%"></code> in the source-code.</p>
<p>I assume I would need to do this through functions.php?</p>
| [
{
"answer_id": 253390,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>You need to use the php <code>preg_replace</code>function in order to transform your url into an snippet.</... | 2017/01/21 | [
"https://wordpress.stackexchange.com/questions/253385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1697/"
] | Goal: convert Facebook url itself (without full code snippet) into Facebook post on website front-end
Problem: The experimental o2 / p2 / breathe theme, by default, converts a full Facebook code snippet in the editor to a full Facebook post on the front-end. Example snippet:
```
<div class="fb-post" data-href="https://www.facebook.com/WordPresscom/posts/10154113693553980" max-width="90%">
```
I would like to instead just be able to post ONLY the url into the editor and have the url wrapped with `<div class="fb-post" data-href=" ... " max-width="90%">` in the source-code.
I assume I would need to do this through functions.php? | Note that Facebook is a registered *oEmbed* provider in the WordPress core.
You could e.g. use the [`pre_oembed_result`](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-oembed.php#L350) filter, before the HTTP request is made, to cancel it and override it to your needs.
Here's an example for Facebook posts:
```
add_filter( 'pre_oembed_result', function ( $result, $url, $args )
{
// override the HTML result for Facebook posts, that will be saved into postmeta table
if( preg_match( '#https?://www\.facebook\.com/.*/posts/.*#i', $url ) )
$result = sprintf(
'<div class="fb-post" data-href="%s">%s</div>',
esc_url( $url ),
esc_url( $url )
);
return $result;
}, 10, 3 );
```
When you paste a Facebook post url, into the post content editor, it will also show the modified oEmbed result, with our snippet.
The oEmbed results are [cached](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L210) by default in the postmeta table, for `DAY_IN_SECONDS` (24 hours).
We can play with the [`oembed_ttl`](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L210) filter, like [here](https://wordpress.stackexchange.com/a/203558/26350), but in the meanwhile we can also filter the cached output with the [`embed_oembed_html`](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/class-wp-embed.php#L239) filter.
Here's an example:
```
add_filter( 'embed_oembed_html', function( $cache, $url, $attr, $post_id )
{
// override the cached HTML result for Facebook posts
if( preg_match( '#https?://www\.facebook\.com/.*/posts/.*#i', $url ) )
$cache = sprintf(
'<div class="fb-post" data-href="%s">%s</div>',
esc_url( $url ),
esc_url( $url )
);
return $cache;
}, 10, 4 );
``` |
253,401 | <p>I am using wordpress ajax and following code not passing parameter value <code>metakey: id</code> to <code>$_POST["metakey"]</code>. So <code>var_dump($_POST)</code> shows <code>array(0) { }</code> and <code>$_REQUEST</code> shows <code>array()</code></p>
<p>if I enter static value of variable in PHP function <code>$key=<any meta
key></code> then its works fine</p>
<pre><code>jQuery(".selectbox").change(function(){
var id = this.id;
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get-mata-value",
metakey: id
}),
success: function( response ) {
jQuery.each(response ,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
});
});
</code></pre>
<p>PHP:</p>
<pre><code>add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$result=
$wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$key
) );
return($result);
exit();
}
</code></pre>
<p>EDIT:</p>
<p>Under chrome developer tool I see </p>
<blockquote>
<p>jquery.js?ver=1.12.4:4 XHR finished loading: POST</p>
</blockquote>
<p>with following error:</p>
<blockquote>
<p>jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to
search for 'length' in</p>
</blockquote>
| [
{
"answer_id": 253406,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p>First of all you should read the codex on <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollo... | 2017/01/21 | [
"https://wordpress.stackexchange.com/questions/253401",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95126/"
] | I am using wordpress ajax and following code not passing parameter value `metakey: id` to `$_POST["metakey"]`. So `var_dump($_POST)` shows `array(0) { }` and `$_REQUEST` shows `array()`
if I enter static value of variable in PHP function `$key=<any meta
key>` then its works fine
```
jQuery(".selectbox").change(function(){
var id = this.id;
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get-mata-value",
metakey: id
}),
success: function( response ) {
jQuery.each(response ,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
});
});
```
PHP:
```
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$result=
$wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$key
) );
return($result);
exit();
}
```
EDIT:
Under chrome developer tool I see
>
> jquery.js?ver=1.12.4:4 XHR finished loading: POST
>
>
>
with following error:
>
> jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to
> search for 'length' in
>
>
> | The issue was with google api as stated in question by showing api related error message
>
> jquery.js?ver=1.12.4:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
>
>
>
So I have added following code snippet in theme functions.php that called previous version of google api. It has solved the issue of passing parameter value. All other code was already fine.
```
//Making jQuery Google API
function modify_jquery() {
if (!is_admin()) {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1');
wp_enqueue_script('jquery');
}
}
add_action('init', 'modify_jquery');
``` |
253,410 | <p>hi i want to display posts by term.
first the code display all the posts:</p>
<pre><code> $aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
);
</code></pre>
<p>so i add another part of code to display posts by term:</p>
<pre><code>$aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => 43
)
)
);
</code></pre>
<p>but its not working its give me an error message<code>:Parse error: syntax error, unexpected ''tax_query''</code></p>
<p>can someone help me?</p>
| [
{
"answer_id": 253411,
"author": "Md. Mrinal Haque",
"author_id": 111354,
"author_profile": "https://wordpress.stackexchange.com/users/111354",
"pm_score": 1,
"selected": false,
"text": "<p>put <code>,</code> in 'order' => 'asc' 'tax_query'</p>\n"
},
{
"answer_id": 253412,
"a... | 2017/01/21 | [
"https://wordpress.stackexchange.com/questions/253410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111459/"
] | hi i want to display posts by term.
first the code display all the posts:
```
$aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
);
```
so i add another part of code to display posts by term:
```
$aProjectArgs = array(
'post_type' => 'uni_project',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'asc'
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => 43
)
)
);
```
but its not working its give me an error message`:Parse error: syntax error, unexpected ''tax_query''`
can someone help me? | put `,` in 'order' => 'asc' 'tax\_query' |
253,428 | <p>I have had a look at the source code of Wordpress, as well as php.net for a possible answer. However, I was not able to get close to finding it.</p>
<p>For the source code, I was assuming I would find it in one of the many files I checked in the wp-includes folder. However, there are way! to many files to look through.</p>
<p>What I want to know if how does Wordpress manage to get Theme/Plugin/Template name and other information from the headers of the specific files? If it were XML data or PHP variables, it would make sense. However the data is places in PHP Comments! How does one read comments?</p>
<pre><code>/*
Theme Name: Twenty Sixteen
Theme URI: https://wordpress.org/themes/twentysixteen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout Version: 1.2
License: GNU General Public License v2 or later
Text Domain: twentysixteen
*/
</code></pre>
<p>One question here on StackOverflow suggested the use of <code>getDocComment()</code> however now another question comes to me mind, first, how do we only get a specific block of comments? </p>
<p>Even if we manage to get all the content of the comment, how do we manage to get the "Theme Name" into a variable and so on?</p>
| [
{
"answer_id": 253440,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>The function is called <a href=\"https://developer.wordpress.org/reference/functions/get_file_data/\" rel=\"nofoll... | 2017/01/21 | [
"https://wordpress.stackexchange.com/questions/253428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48443/"
] | I have had a look at the source code of Wordpress, as well as php.net for a possible answer. However, I was not able to get close to finding it.
For the source code, I was assuming I would find it in one of the many files I checked in the wp-includes folder. However, there are way! to many files to look through.
What I want to know if how does Wordpress manage to get Theme/Plugin/Template name and other information from the headers of the specific files? If it were XML data or PHP variables, it would make sense. However the data is places in PHP Comments! How does one read comments?
```
/*
Theme Name: Twenty Sixteen
Theme URI: https://wordpress.org/themes/twentysixteen/
Author: the WordPress team
Author URI: https://wordpress.org/
Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout Version: 1.2
License: GNU General Public License v2 or later
Text Domain: twentysixteen
*/
```
One question here on StackOverflow suggested the use of `getDocComment()` however now another question comes to me mind, first, how do we only get a specific block of comments?
Even if we manage to get all the content of the comment, how do we manage to get the "Theme Name" into a variable and so on? | The function is called [`get_file_data`](https://developer.wordpress.org/reference/functions/get_file_data/), it uses a regular expression to parse the text and find headers. |
253,445 | <p>I have a custom endpoint where I want to change HTTP response status to 404 in certain scenarios (e.g post does not exist). How can I do that? Here is an example of custom endpoint:</p>
<pre><code>function af_news_single( \WP_REST_Request $data ) {
global $wpdb;
$year = (int) $data['year'];
$month = (int) $data['month'];
$day = (int) $data['day'];
$slug = $data['slug'];
$date = "{$year}-{$month}-{$day}";
$news = $wpdb->get_row(
$wpdb->prepare(
"SELECT
DATE_FORMAT(post_date, %s) as `post_date`,
`post_title`,
`post_name`,
`post_content`
FROM {$wpdb->posts}
WHERE
`post_status` = 'publish' AND
`post_type` = 'post' AND
`post_name` = %s AND
`post_date` BETWEEN %s AND %s + INTERVAL 1 DAY
LIMIT 1
", '%Y-%m-%dT%TZ', $slug, $date, $date
)
);
if ( $news ) {
$news->post_title = qtranxf_translate( $news->post_title );
$news->post_content = wpautop( qtranxf_translate( $news->post_content ) );
} else { /* How to change response code? */ }
return [ 'data' => $news ];
}
</code></pre>
<p>How can I change response code in this function?</p>
| [
{
"answer_id": 253472,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 6,
"selected": true,
"text": "<p>You can return a <code>WP_Error</code> object in which you define the status code. Here's a snippet from <a hr... | 2017/01/21 | [
"https://wordpress.stackexchange.com/questions/253445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67305/"
] | I have a custom endpoint where I want to change HTTP response status to 404 in certain scenarios (e.g post does not exist). How can I do that? Here is an example of custom endpoint:
```
function af_news_single( \WP_REST_Request $data ) {
global $wpdb;
$year = (int) $data['year'];
$month = (int) $data['month'];
$day = (int) $data['day'];
$slug = $data['slug'];
$date = "{$year}-{$month}-{$day}";
$news = $wpdb->get_row(
$wpdb->prepare(
"SELECT
DATE_FORMAT(post_date, %s) as `post_date`,
`post_title`,
`post_name`,
`post_content`
FROM {$wpdb->posts}
WHERE
`post_status` = 'publish' AND
`post_type` = 'post' AND
`post_name` = %s AND
`post_date` BETWEEN %s AND %s + INTERVAL 1 DAY
LIMIT 1
", '%Y-%m-%dT%TZ', $slug, $date, $date
)
);
if ( $news ) {
$news->post_title = qtranxf_translate( $news->post_title );
$news->post_content = wpautop( qtranxf_translate( $news->post_content ) );
} else { /* How to change response code? */ }
return [ 'data' => $news ];
}
```
How can I change response code in this function? | You can return a `WP_Error` object in which you define the status code. Here's a snippet from [the REST API documentation](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#return-value):
```
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
```
In your case you could do something like:
```
return new WP_Error( 'page_does_not_exist', __('The page you are looking for does not exist'), array( 'status' => 404 ) );
``` |
253,473 | <p>Suppose I have created an app that uses WordPress REST API plugin and displays the posts from the WordPress site.</p>
<p>Now, if I find the WordPress site which is having the WP REST API plugin and I am able to fetch the data from it (only displaying the data into the app, not storing it). Is it legal to do so as per WordPress or REST API license?</p>
| [
{
"answer_id": 253472,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 6,
"selected": true,
"text": "<p>You can return a <code>WP_Error</code> object in which you define the status code. Here's a snippet from <a hr... | 2017/01/22 | [
"https://wordpress.stackexchange.com/questions/253473",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111492/"
] | Suppose I have created an app that uses WordPress REST API plugin and displays the posts from the WordPress site.
Now, if I find the WordPress site which is having the WP REST API plugin and I am able to fetch the data from it (only displaying the data into the app, not storing it). Is it legal to do so as per WordPress or REST API license? | You can return a `WP_Error` object in which you define the status code. Here's a snippet from [the REST API documentation](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#return-value):
```
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
```
In your case you could do something like:
```
return new WP_Error( 'page_does_not_exist', __('The page you are looking for does not exist'), array( 'status' => 404 ) );
``` |